在设计模式中,工厂模式是用的比较多的一种模式,工厂模式一般可分为”简单工厂”、”工厂方法”、“抽象工厂方法”模式模式,下面主要对比一下”简单工厂”、”工厂方法”的区别和优缺点
- 简单工厂模式
-
先定义一个IOperation接口
public interface IOperation {
double caculate(double num1, double num2);
} -
定义一些实现IOperation接口的算法
- 加法运算 :
public class OperationAdd implements IOperation {
@Override
public double caculate(double num1, double num2) {
return num1 + num2;
}
}- 减法运算:
public class OperationSub implements IOperation {
@Override
public double caculate(double num1, double num2) {
return num1 - num2;
}
} - 乘法运算:
public class OperationMulti implements IOperation {
@Override
public double caculate(double num1, double num2) {
return num1 * num2;
}
}
- 加法运算 :
-
工厂类
public class OperationFactory {
public static final int TYPE_ADD = 1;
public static final int TYPE_SUB = 2;
public static final int TYPE_MULTI = 3;
public static final int TYPE_DIV = 4;
public static IOperation createOperation(int type){
if (type == TYPE_ADD){
return new OperationAdd();
}else if (type == TYPE_SUB){
return new OperationSub();
}else if (type == TYPE_MULTI){
return new OperationMulti();
}else if (type == TYPE_DIV){
return new OperationDiv();
}
return null;
}
}
3.使用
IOperation operation = OperationFactory.createOperation(OperationFactory.TYPE_ADD);
System.out.println("operation add = "+ operation.caculate(1,2));
operation = OperationFactory.createOperation(OperationFactory.TYPE_SUB);
System.out.println("operation sub = "+ operation.caculate(1,2));
优缺点: 简单工厂模式实现了生成产品类的代码跟客户端分离,在工程类里面可以添加所需生成产品的逻辑。缺点是每次增加一种算法类型,都需要修改工厂类,不符合开闭原则 ()
- 工厂方法模式
1.定义一个工厂接口用于实现生成算法
public interface IFactory {
IOperation createOperation();
}
2.产生运算的工厂
加法工厂
public class AddFactory implements IFactory{
@Override
public IOperation createOperation() {
return new OperationAdd();
}
}
减法工厂
public class SubFactory implements IFactory{
@Override
public IOperation createOperation() {
return new OperationSub();
}
}
乘法工厂
public class SubFactory implements IFactory{
@Override
public IOperation createOperation() {
return new OperationSub();
}
}
3.使用
IFactory factory = new AddFactory();
IOperation operation = factory.createOperation();
System.out.println("add factory: "+ operation.caculate(2,5));
factory = new SubFactory();
operation = factory.createOperation();
System.out.println("sub factory: "+ operation.caculate(2,5));
4.优缺点
工厂方法中,我们把生成算法实现类的时间延迟,就是通过对应的工厂来生成对应的算法类,这样就做到了无论需要增加多少算法实现类,都可以通过增加工厂实现类来实现,这种设计方式符合 “开闭”原则。缺点就是当算法过多的时候,需要定义很多算法对应的工厂类。
网友评论