虚线箭头指向依赖;
实线箭头指向关联;
虚线三角指向接口;
实线三角指向父类;
空心菱形能分离而独立存在,是聚合;
实心菱形精密关联不可分,是组合;
上面是uml的语法。
在画类图的时候,理清类和类之间的关系是重点。类的关系有泛化(generalization)、实现(realization)、依赖(dependency)和关联(association)。其中关联又分为一般关联关系和聚合关系(aggregation),合成关系(composition)。下面我们结合实例理解这些关系。注意【代码表现】里面的描述!
比如《组合模式》的uml图
将对象组合成树形结构以表示“部分-整体”的层次结构。composite 使得用户对单个对象和组
合对象的使用具有一致性。
根据uml中的【代码表现】写出对应示例代码
// composite pattern -- structural example using system; using system.collections; namespace dofactory.gangoffour.composite.structural { // mainapp test application class mainapp { static void main() { // create a tree structure composite root = new composite("root"); root.add(new leaf("leaf a")); root.add(new leaf("leaf b")); composite comp = new composite("composite x"); comp.add(new leaf("leaf xa")); comp.add(new leaf("leaf xb")); root.add(comp); root.add(new leaf("leaf c")); // add and remove a leaf leaf leaf = new leaf("leaf d"); root.add(leaf); root.remove(leaf); // recursively display tree root.display(1); // wait for user console.read(); } } // "component" abstract class component { protected string name; // constructor public component(string name) { this.name = name; } public abstract void add(component c); public abstract void remove(component c); public abstract void display(int depth); } // "composite" class composite : component { private arraylist children = new arraylist(); // constructor public composite(string name) : base(name) { } public override void add(component component) { children.add(component); } public override void remove(component component) { children.remove(component); } public override void display(int depth) { console.writeline(new string('-', depth) + name); // recursively display child nodes foreach (component component in children) { component.display(depth + 2); } } } // "leaf" class leaf : component { // constructor public leaf(string name) : base(name) { } public override void add(component c) { console.writeline("cannot add to a leaf"); } public override void remove(component c) { console.writeline("cannot remove from a leaf"); } public override void display(int depth) { console.writeline(new string('-', depth) + name); } } }
设计模式的主要思想其实很简单,就是:测试驱动开发。测试先行。意思是:先写测试代码,再去实现代码。
所以先写单元测试是很重要的,因为选用什么设计模式,不是容易就决定的。还是根据业务场景去决定的。而且业务需求随时都变
化。所以你的代码要经受得住各种变化。设计模式跟着需求变化而变化。这就是xp的关键,拥抱变化。那如何确保每次修改后代码
能稳定地运行呢?那就行写好单元测试。尽量覆盖尽量多的测试用例,每次修改完跑一下单元测试。不用管要用什么设计模式。只
要你的代码都能通过,你的代码肯定用了很多设计模式在里面,不然不可能做到拥抱变化(就是解耦)。设计模式的目标就是拥抱变化。
总结内容参考博文
打赏
本文链接
如对本文有疑问, 点击进行留言回复!!
网友评论