工厂方法模式类图
代码示例
假设实现一个计算器,支持加法运算和减法运算。
计算器接口
public interface IOperation {
int getResult(int a, int b);
}
加法运算
public class AddOperation implements IOperation{
@Override
public int getResult(int a, int b) {
return a + b;
}
}
减法运算
public class SubOperation implements IOperation{
@Override
public int getResult(int a, int b) {
return a - b;
}
}
方法工厂接口
public interface IMethodFactory {
IOperation createOperation();
}
加法工厂
public class AddFactory implements IMethodFactory{
@Override
public IOperation createOperation() {
return new AddOperation();
}
}
减法工厂
public class SubFactory implements IMethodFactory{
@Override
public IOperation createOperation() {
return new SubOperation();
}
}
客户端代码
public static void main(String[] args) {
// 加法运算
IMethodFactory addFactory = new AddFactory();
IOperation addOperation = addFactory.createOperation();
int addRes = addOperation.getResult(10, 10);
// 减法运算
IMethodFactory subFactory = new SubFactory();
IOperation subOperation = subFactory.createOperation();
int subRes = subOperation.getResult(10, 10);
}
后续如果需要扩展乘法运算、除法运算,不需要修改现有代码,只需要增加对应的运算类和工厂类即可。
优缺点
优点:对扩展开放;对修改关闭。
缺点:产生很多的类文件。