源自:
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();
}
}