在普通的简单工厂方法中,简单工厂在创建对象时进行了必要的逻辑判断,选择实例化相关的类,但是这个操作违背了开闭原则,每次添加一种新的类型都需要修改工厂类. 所以可以使用工厂方法模式将实例化这个行为延迟到其子类,定义一个用于创建对象的接口,让接口的子类来决定实例化哪一个类. 如果添加新的类型,只需要添加新的类型的工厂就可以了.
IFactory -- 工厂接口
一个具体的Operation类对应一个具体的OperationFactory, Operation1 <-----> Operation1Factory, Operation2 <-----> Operation2Factory
import java.util.*;
abstract class Operation {
public abstract void Operate();
}
class Operation1 extends Operation {
public void Operate() {
System.out.println("Class Operation1 -- operate");
}
}
class Operation2 extends Operation {
public void Operate() {
System.out.println("Class Operation2 -- operate");
}
}
class Operation3 extends Operation {
public void Operate() {
System.out.println("Class Operation3 -- operate");
}
}
interface IFactory {
public Operation CreateOperation();
}
class Operation1Factory implements IFactory {
public Operation CreateOperation() {
return new Operation1();
}
}
class Operation2Factory implements IFactory {
public Operation CreateOperation() {
return new Operation2();
}
}
class Operation3Factory implements IFactory {
public Operation CreateOperation() {
return new Operation3();
}
}
public class FactoryMethod {
public static void main(String[] args) {
IFactory operFactory = new Operation1Factory();
Operation oper = operFactory.CreateOperation();
oper.Operate();
}
}