虚线箭头指向依赖;
实线箭头指向关联;
虚线三角指向接口;
实线三角指向父类;
空心菱形能分离而独立存在,是聚合;
实心菱形精密关联不可分,是组合;html
上面是UML的语法。
在画类图的时候,理清类和类之间的关系是重点。类的关系有泛化(Generalization)、实现(Realization)、依赖(Dependency)和关联(Association)。其中关联又分为通常关联关系和聚合关系(Aggregation),合成关系(Composition)。下面咱们结合实例理解这些关系。注意【代码表现】里面的描述!node
好比《组合模式》的UML图设计模式
将对象组合成树形结构以表示“部分-总体”的层次结构。Composite 使得用户对单个对象和组
合对象的使用具备一致性。app
根据UML中的【代码表现】写出对应示例代码ide
// 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的关键,拥抱变化。那如何确保每次修改后代码
能稳定地运行呢?那就行写好单元测试。尽可能覆盖尽可能多的测试用例,每次修改完跑一下单元测试。不用管要用什么设计模式。只
要你的代码都能经过,你的代码确定用了不少设计模式在里面,否则不可能作到拥抱变化(就是解耦)。设计模式的目标就是拥抱变化。单元测试
总结内容参考博文 http://www.javashuo.com/article/p-xkjmycsn-o.html测试
打赏this