您的位置:首页 > 编程语言 > Java开发

Java设计模式-----Factory Method模式

2008-06-06 11:17 405 查看
源自:http://www.blogjava.net/flustar/archive/2007/11/29/factoryMethod.html

Factory Method模式:

定义一个用于创建对象的接口,让子类决定实例化哪一个类。FactoryMethod使一个类的实例化延迟到其子类。

例子:

public abstract class Ball {
protected  abstract  void play();
}

public class Basketball extends Ball {

protected void play() {
System.out.println("play the basketball");
}
}

public class Football extends Ball {

protected void play() {
System.out.println("play the football");
}
}

public abstract class BallFactory {
protected  abstract Ball makeBall();
}

public class BasketballFact extends BallFactory {

protected Ball makeBall() {
return new Basketball();
}
}

public class FootballFact extends BallFactory {

protected Ball makeBall() {
return new Football();
}
}

public class Client {

public static void main(String[] args) {

BallFactory ballFactory = new BasketballFact();
Ball basketball = ballFactory.makeBall();
basketball.play();

ballFactory = new FootballFact();
Ball football = ballFactory.makeBall();
football.play();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: