设计模式-单一职责模式
发布时间:2020-12-13 23:04:31 所属栏目:百科 来源:网络整理
导读:最近在很多场合都看见设计模式的影子,一直以来,都投入主要时间在搞算法与数据结构,很来发现设计模式真的很重要。有的时候代码的可维护、可重用、可扩展确实胜过单纯的算法效率高。所以拾起大牛书籍《大话设计模式》同时参考网上诸大牛的博客,开始我的设
最近在很多场合都看见设计模式的影子,一直以来,都投入主要时间在搞算法与数据结构,很来发现设计模式真的很重要。有的时候代码的可维护、可重用、可扩展确实胜过单纯的算法效率高。所以拾起大牛书籍《大话设计模式》同时参考网上诸大牛的博客,开始我的设计模式之旅。
今天先介绍一下单一职责模式。 概念: 就一个类而言应该只有一个因其他变化的原因。
流程: 问题由来:设类或接口类C负责两个不同不同的职责:职责T1,职责T2。当由于职责T1需求改变进而需要修改类C时,可能导致职责T2收到不可预知的影响。 解决方案:分别建立两个类C1、C2,分管职责T1,T2。 优缺点:
1.优点:
(1)、降低类的复杂度;
(2)、
易维护、易扩展、可读性强
2.缺点:
使类或接口的数目增加,
难以控制。
示例代码
下面代码就没有遵循单一职责模式,如Operation即完成了+又完成了-。
package Pattern; import java.util.Scanner; class Operation { String operationName; public Operation(String tempOperationName) { operationName = tempOperationName; } public int GetResult(int opA,int opB) { if (operationName.equals("+")) return opA + opB; else return opA - opB; } } public class Pattern { public static void main(String[] args) { try { Scanner input = new Scanner(System.in); int opA,opB,result; opA = input.nextInt(); opB = input.nextInt(); Operation myOperation = new Operation("+"); result = myOperation.GetResult(opA,opB); System.out.println(result); } catch (Exception e) { e.printStackTrace(); } } } 尝试单一职责模式可以拆开。 package Pattern; import java.util.Scanner; class AddOperation { public int GetResult(int opA,int opB) { return opA + opB; } } class SubOperation { public int GetResult(int opA,int opB) { return opA - opB; } } public class Pattern { public static void main(String[] args) { try { Scanner input = new Scanner(System.in); int opA,result; opA = input.nextInt(); opB = input.nextInt(); AddOperation myAddOperation = new AddOperation(); result = myAddOperation.GetResult(opA,opB); System.out.println(result); opA = input.nextInt(); opB = input.nextInt(); SubOperation mySubOperation = new SubOperation(); result = mySubOperation.GetResult(opA,opB); System.out.println(result); } catch (Exception e) { e.printStackTrace(); } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |