工厂方法模式实际上是简单工厂的一种延伸模式,属于类的创建型模式又被称为多态工厂模式 。
工厂方法模式的意义是定义一个创建产品对象的工厂接口,将实际创建工作推迟到子类当中。核心工厂类不再负责产品的创建,这样核心类成为一个抽象工厂角色,仅负责具体工厂子类必须实现的接口。
下面来看结构图(摘自 程杰 大话设计模式 )
下面来看代码:
1、水果接口 和 水果工厂接口
// 水果接口
public interface Fruit {
public void getName();
}
// 水果工厂接口
public interface FruitFactory {
public Fruit getFruit();
}
2、具体水果
//苹果
public class Apple implements Fruit{
public void getName(){
System.out.println("苹果");
}
}
//香蕉
public class Banana implements Fruit{
public void getName(){
System.out.println("香蕉");
}
}
3、具体水果工厂
// 苹果工厂
public class AppleFactory implements FruitFactory {
public Fruit getFruit() {
return new Apple();
}
}
// 香蕉工厂
public class BananaFactory implements FruitFactory {
public Fruit getFruit() {
return new Banana();
}
}
4、使用
public static void main(String[] args) {
//获得AppleFactory
FruitFactory ff = new AppleFactory();
//通过AppleFactory来获得Apple实例对象
Fruit apple = ff.getFruit();
apple.get();
//获得BananaFactory
FruitFactory ff2 = new BananaFactory();
Fruit banana = ff2.getFruit();
banana.get();
}
总结:
工厂方法是对简单工厂进一步抽象化,使得工厂方法模式可以使系统在不修改具体工厂角色的情况下引进新的产品。遵循开发-封闭原则。