相对于简单工厂模式,工厂方法稍微比较繁琐。在GOF设计模式书中的定义如下:
"Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses"
简单翻译一下,“定义一个接口用于创建对象,但是让子类决定去实例化那个类,工厂方法让一个类将实例化延迟到子类。下面这个图是网上扣的图,并非我画的。
根据定义:
1、Define an interface for creating an object 定义一个接口用于创建一个对象
public interface IFactory {
IFan getFan();
}
2、let subclasses decide which class to instantiate,让子类决定实例化那个类
public class TableFanFactory implements IFactory{
@Override
public IFan getFan() {
return new TableFan();
}
}
public class CeilingFanFactory implements IFactory{
@Override
public IFan getFan() {
return new CellingFan();
}
}
3、Factory Method lets a class defer instantiation to subclasses,让一个类延迟实例化到子类
public static void main(String[] args) {
CeilingFanFactory ceilingFactory = new CeilingFanFactory();
IFan fan = ceilingFactory.getFan();
}
跟简单工厂模式对比,你会发现,客户端需要创建指定的实例的时候需要使用对应的工厂,而并非只有一个工厂,简单工厂只有一个工厂类,只有一个工厂,那么就意味着,当有新需求变动的时候肯定会改动到之前已有的功能,对于这违反了对修改关闭,对拓展开放的原则。会带入一些不稳定的因素。现在因为使用多个工厂,每个工厂的功能都不同,当需要新增产品时,只需要拓展一个新工厂,然后在调用端使用对应的工厂,这就很符合开闭原则。