工厂方法模式的实质是“定义一个创建对象的接口,但让实现这个接口的类来决定实例化哪个类。工厂方法让类的实例化推迟到子类中进行。
UML类图
代码实现
IFactory
1 2 3 4 5 6 7
| package com.lei.designpatterns.factorymethod;
import com.lei.designpatterns.simplefactory.Operation;
public interface IFactory { Operation createOperation(); }
|
AddFactory
1 2 3 4 5 6 7 8 9 10 11
| package com.lei.designpatterns.factorymethod;
import com.lei.designpatterns.simplefactory.Operation; import com.lei.designpatterns.simplefactory.OperationAdd;
public class AddFactory implements IFactory { @Override public Operation createOperation() { return new OperationAdd(); } }
|
SubFactory
1 2 3 4 5 6 7 8 9 10 11
| package com.lei.designpatterns.factorymethod;
import com.lei.designpatterns.simplefactory.Operation; import com.lei.designpatterns.simplefactory.OperationSub;
public class SubFactory implements IFactory { @Override public Operation createOperation() { return new OperationSub(); } }
|
MulFactory
1 2 3 4 5 6 7 8 9 10 11
| package com.lei.designpatterns.factorymethod;
import com.lei.designpatterns.simplefactory.Operation; import com.lei.designpatterns.simplefactory.OperationMul;
public class MulFactory implements IFactory { @Override public Operation createOperation() { return new OperationMul(); } }
|
DivFactory
1 2 3 4 5 6 7 8 9 10 11
| package com.lei.designpatterns.factorymethod;
import com.lei.designpatterns.simplefactory.Operation; import com.lei.designpatterns.simplefactory.OperationDiv;
public class DivFactory implements IFactory { @Override public Operation createOperation() { return new OperationDiv(); } }
|
附录
依赖简单工厂模式