天天看点

抽象工厂模式

《大话设计模式》阅读笔记和总结。原书是C#编写的,本人用Java实现了一遍,包括每种设计模式的UML图实现和示例代码实现。

目录:

设计模式 Github地址: DesignPattern

说明

定义:抽象工厂模式(Abstract Factory),提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。

UML图:

抽象工厂模式

抽象工厂模式UML图.png

示例

例子:依然使用简单工厂模式的示例,用程序实现输入两个数和运算符号,得到结果。

代码实现:

利用反射改造简单工厂模式,去掉分支判断的逻辑

public class OperationFactory {
    private static Map<String, Class<?>> allOperationMaps = new HashMap<String, Class<?>>();

    public static void fillMap() {
        allOperationMaps.put("+", OperationAdd.class);
        allOperationMaps.put("-", OperationSub.class);
        allOperationMaps.put("*", OperationMul.class);
        allOperationMaps.put("/", OperationDiv.class);
    }

    public static Operation createOperation(String operator)
            throws InstantiationException, IllegalAccessException {
        Operation operation;

        fillMap();
        Class<?> operationClass = allOperationMaps.get(operator);

        if (operationClass == null) {
            throw new RuntimeException("unsupported operation");
        }

        operation = (Operation) operationClass.newInstance();

        return operation;
    }
}

           

客户端代码

public class Main {
    public static void main(String[] args) throws InstantiationException,
            IllegalAccessException {
        Operation operation = OperationFactory.createOperation("/");

        operation.setNumberA(7);
        operation.setNumberB(8);

        System.out.println(operation.getNumberA());
    }
}