设计模式--组合模式
生活随笔
收集整理的這篇文章主要介紹了
设计模式--组合模式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
定義:
將對象組合成樹形結構以表示"部分--整體"的層次結構.組合結構使得用戶對單個對象和組合對象的使用具有一致性.關鍵詞:
Composite
結構圖:
應用場景:
表達的對象成"整體-部分"層次結構時.
即表達的對象最后結果承樹形時,可以采用組合模式.
例如:
中國移動下屬3個品牌:全球通,神州行,動感地帶.
同時,中國移動下屬有北京移動,天津移動,江蘇移動等分公司.下屬各分公司又包含3個品牌.
各分公司又含有下屬單位及相關品牌.
這種樹狀結構的層次使用組合模式.
實際上,品牌和公司并不是一個類可以描述的,但是為了使客戶處理起來方便,可以不分復雜元素和簡單元素,也可以使之如此設計.
例子:
類圖:
代碼: public abstract class Mobile {protected string name;public Mobile(string name){this.name = name;}public abstract void Add(Mobile m);public abstract void Remove(Mobile m);public abstract void Duty(int depth); }public class Easyown : Mobile {public Easyown(string name) : base(name){}public override void Add(Mobile m){}public override void Remove(Mobile m){}public override void Duty(int depth){HttpContext.Current.Response.Write(new string('-', depth) + name + "(輕松由我,神州行!)<br/>");} }public class M_Zone : Mobile {public M_Zone(string name): base(name){}public override void Add(Mobile m){}public override void Remove(Mobile m){}public override void Duty(int depth){HttpContext.Current.Response.Write(new string('-', depth) + name + "(我的地盤,聽我的!)<br/>");} }public class GoTone : Mobile {public GoTone(string name): base(name){}public override void Add(Mobile m){}public override void Remove(Mobile m){}public override void Duty(int depth){HttpContext.Current.Response.Write(new string('-', depth) + name + "(我能!)<br/>");} }public class MobileCompany : Mobile {List<Mobile> al = new List<Mobile>(10);public MobileCompany(string name): base(name){}public override void Add(Mobile m){al.Add(m);}public override void Remove(Mobile m){al.Remove(m);}public override void Duty(int depth){HttpContext.Current.Response.Write(new string('-', depth) + name + "<br/>");foreach(Mobile m in al){m.Duty(depth+2);}} }頁面調用: protected void Page_Load(object sender, EventArgs e){Mobile m1 = new MobileCompany("中國移動");m1.Add(new Easyown("神州行"));m1.Add(new M_Zone("動感地帶"));m1.Add(new GoTone("全球通"));Mobile m2 = new MobileCompany("江蘇移動");m2.Add(new Easyown("神州行"));m2.Add(new M_Zone("動感地帶"));m2.Add(new GoTone("全球通"));Mobile m3 = new MobileCompany("四川移動");m3.Add(new Easyown("神州行"));m3.Add(new M_Zone("動感地帶"));m3.Add(new GoTone("全球通"));Mobile m31 = new MobileCompany("成都移動");m31.Add(new Easyown("神州行"));m31.Add(new M_Zone("動感地帶"));m31.Add(new GoTone("全球通"));m3.Add(m31);m1.Add(m2);m1.Add(m3);m1.Duty(0);}效果:
轉載于:https://www.cnblogs.com/oneword/archive/2009/06/30/1513986.html
總結
以上是生活随笔為你收集整理的设计模式--组合模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 线程安全的signals
- 下一篇: 在Visual Studio中构建启动时