虛線箭頭指向依賴;
實線箭頭指向關聯;
虛線三角指向接口;
實線三角指向父類;
空心菱形能分離而獨立存在,是聚合;
實心菱形精密關聯不可分,是組合;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