@linux1s1s
2019-02-18T19:06:21.000000Z
字数 2115
阅读 1636
Base
2017-01
Base Time-Design Patterns-Factory Method文中详细介绍了静态工厂方法模式,这个模式做到了可复用、可维护、可扩展。但是该种模式在新增算法的时候会明显违反开闭原则
,而抽象工厂方法就是解决这个问题的。
开闭原则
的基础上实现上面的需求。为了不修改静态工厂,我们将工厂抽象,这样每个算法对应一个工厂的具体实现,新增算法就会新增工厂,这样就完全遵从了开闭原则
。
首先是算法接口Operation
Operation.java
public interface Operation {
float execute(float x, float y);
}
Operation实现类,实现具体的算法。
AddOperation.java
public class AddOperation implements Operation {
@Override
public float execute(float x, float y) {
return x + y;
}
}
SubOperation.java
public class SubOperation implements Operation {
@Override
public float execute(float x, float y) {
return x - y;
}
}
MultipleOperation.java
public class MultipleOperation implements Operation {
@Override
public float execute(float x, float y) {
return x * y;
}
}
DivOperation.java
public class DivOperation implements Operation {
@Override
public float execute(float x, float y) {
return x / y;
}
}
接下来是工厂接口IFactory
IFactory.java
public interface IFactory {
Operation createOperation();
}
IFactory接口的实现类,实现具体的工厂方法
AddFactory.java
public class AddFactory implements IFactory {
@Override
public Operation createOperation() {
return new AddOperation();
}
}
SubFactory.java
public class SubFactory implements IFactory {
@Override
public Operation createOperation() {
return new SubOperation();
}
}
MultipleFactory.java
public class MultipleFactory implements IFactory {
@Override
public Operation createOperation() {
return new MultipleOperation();
}
}
DivFactory.java
public class DivFactory implements IFactory {
@Override
public Operation createOperation() {
return new DivOperation();
}
}
最后是TestCase
public class TestCase {
public static void main(String[] args) {
float x = 3;
float y = 4;
String op = "-";
Operation operation;
IFactory factory;
if ("+".equals(op)) {
factory = new AddFactory();
} else if ("-".equals(op)) {
factory = new SubFactory();
} else if ("*".equals(op)) {
factory = new MultipleFactory();
} else if ("/".equals(op)) {
factory = new DivFactory();
} else {
factory = null;
}
if (factory != null) {
operation = factory.createOperation();
} else {
operation = null;
}
if (operation != null) {
operation.execute(x, y);
} else {
Log.e("factory", "Operation illegal");
}
}
}
抽象工厂方法模式遵循了开放-封闭原则,其实它是将判断工作转移到了客户端调用之处,这样保证了工厂体系的完整性。而简单工厂模式需要在工厂类里来判断选择哪个运算类。
参考
工厂方法模式 部分改动,特此说明。