您现在的位置是:首页 > 文章详情

抽象工厂模式

日期:2018-07-28点击:344

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

说明

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

UML图:

img_1f7f6a5e0bbc3436f5e85b1e646f8ad6.png
抽象工厂模式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()); } } 
原文链接:https://yq.aliyun.com/articles/656004
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章