概念
在对简单工厂的抽象时,如果我们将条件判断改由工厂的抽象,将工厂的选择交给调用端,那么久出现了工厂方法。
所以工厂方法是简单工厂的扩展;简单工厂是工厂方法的特例。
示例
产品抽象
interface Car {}
class Jeep implements Car {}
class Porsche implements Car {}
工厂抽象
interface Producer {
Car produce();
}
class JeepProducer implements Producer {
@Override public Car produce() { return new Jeep(); }
}
class PorscheProducer implements Producer {
@Override public Car produce() { return new Porsche(); }
}
Client
public class Main {
public static void main(String[] args) {
Producer producer1 = new JeepProducer();
Car jeep = producer1.produce();
Producer producer2 = new PorscheProducer();
Car porsche = producer2.produce();
}
}
网友评论