简单工厂模式

简单工厂模式(simple factory)是类的创建模式,又叫静态工厂方法(static factory method)模式。
简单工厂模式就是由一个工厂类根据传入的参数决定创建哪一种的产品类。

比如说一个计算器,有四种操作符号,如果是简单工厂模式:

代理模式

代码类似如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class OperationFactory {
public static Operation createOperation(String operation) {
Operation oper = null;
if (operation.equals("+")) {
return new OperationAdd();
}
if (operation.equals("-")) {
return new OperationSub();
}
if (opeartion.equals("*")) {
return new OperationMul();
}
if (operation.equals("/")) {
return new OperationDiv();
}
}
}
调用:
Operation oper;
oper = OperationFactory.createOperation("+");
oper.NumberA = 1;
oper.NumberB = 2;
long result = oper.GetResult();

工厂方法模式

工厂方法模式就是定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
先建立一个工厂接口:

1
2
3
public interface IFactory {
Operation CreateOperation();
}

然后给每一个运算符都建立一个具体的工厂去实现这个接口:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class AddFactory implements IFactory {
public Operation CreateOperation() {
return new OperationAdd();
}
}
public class SubFactory implements IFactory {
public Operation CreateOperation() {
return new OperationSub();
}
}
public class MulFactory implements IFactory {
public Operation CreateOperation() {
return new OperationSub();
}
}
public class DivFactory implements IFactory {
public Operation CreateOperation() {
return new OperationDiv();
}
}