[关闭]
@linux1s1s 2019-02-18T11:06:21.000000Z 字数 2115 阅读 1512

Base Time-Design Patterns-Abstract Factory Method

Base 2017-01


Base Time-Design Patterns-Factory Method文中详细介绍了静态工厂方法模式,这个模式做到了可复用、可维护、可扩展。但是该种模式在新增算法的时候会明显违反开闭原则,而抽象工厂方法就是解决这个问题的。

需求

工厂抽象

为了不修改静态工厂,我们将工厂抽象,这样每个算法对应一个工厂的具体实现,新增算法就会新增工厂,这样就完全遵从了开闭原则

UML

此处输入图片的描述

源码

首先是算法接口Operation
Operation.java

  1. public interface Operation {
  2. float execute(float x, float y);
  3. }

Operation实现类,实现具体的算法。
AddOperation.java

  1. public class AddOperation implements Operation {
  2. @Override
  3. public float execute(float x, float y) {
  4. return x + y;
  5. }
  6. }

SubOperation.java

  1. public class SubOperation implements Operation {
  2. @Override
  3. public float execute(float x, float y) {
  4. return x - y;
  5. }
  6. }

MultipleOperation.java

  1. public class MultipleOperation implements Operation {
  2. @Override
  3. public float execute(float x, float y) {
  4. return x * y;
  5. }
  6. }

DivOperation.java

  1. public class DivOperation implements Operation {
  2. @Override
  3. public float execute(float x, float y) {
  4. return x / y;
  5. }
  6. }

接下来是工厂接口IFactory
IFactory.java

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

IFactory接口的实现类,实现具体的工厂方法
AddFactory.java

  1. public class AddFactory implements IFactory {
  2. @Override
  3. public Operation createOperation() {
  4. return new AddOperation();
  5. }
  6. }

SubFactory.java

  1. public class SubFactory implements IFactory {
  2. @Override
  3. public Operation createOperation() {
  4. return new SubOperation();
  5. }
  6. }

MultipleFactory.java

  1. public class MultipleFactory implements IFactory {
  2. @Override
  3. public Operation createOperation() {
  4. return new MultipleOperation();
  5. }
  6. }

DivFactory.java

  1. public class DivFactory implements IFactory {
  2. @Override
  3. public Operation createOperation() {
  4. return new DivOperation();
  5. }
  6. }

最后是TestCase

  1. public class TestCase {
  2. public static void main(String[] args) {
  3. float x = 3;
  4. float y = 4;
  5. String op = "-";
  6. Operation operation;
  7. IFactory factory;
  8. if ("+".equals(op)) {
  9. factory = new AddFactory();
  10. } else if ("-".equals(op)) {
  11. factory = new SubFactory();
  12. } else if ("*".equals(op)) {
  13. factory = new MultipleFactory();
  14. } else if ("/".equals(op)) {
  15. factory = new DivFactory();
  16. } else {
  17. factory = null;
  18. }
  19. if (factory != null) {
  20. operation = factory.createOperation();
  21. } else {
  22. operation = null;
  23. }
  24. if (operation != null) {
  25. operation.execute(x, y);
  26. } else {
  27. Log.e("factory", "Operation illegal");
  28. }
  29. }
  30. }

小结

抽象工厂方法模式遵循了开放-封闭原则,其实它是将判断工作转移到了客户端调用之处,这样保证了工厂体系的完整性。而简单工厂模式需要在工厂类里来判断选择哪个运算类。

参考
工厂方法模式 部分改动,特此说明。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注