标签:
一、定义
将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
二、实例:总店—加盟店
总店和加盟店实行的会员制度一样,但是总店和加盟店又是一个层级关系。这样的关系使得形成了一张树状图。
根节点—子节点—叶子
2.1 抽象组合关系
//--------------组合------------------- public abstract class Company { public string ShopID { get; set; } public Company(string shopID) { ShopID = shopID; } public abstract void AddShop(Company shop); public abstract void RemoveShop(Company shop); public abstract void DisplayShops(); }
2.2 定义 节点和叶子
//--------------节点-------------------- public class Headquarters : Company { List<Company> shops = new List<Company>(); public Headquarters(string shopID) : base(shopID) { } public override void AddShop(Company shop) { shops.Add(shop); } public override void RemoveShop(Company shop) { shops.Remove(shop); } public override void DisplayShops() { foreach (var shop in shops) { Console.WriteLine("展示店铺:"+shop.ShopID); } } }
//-------------------叶子--------------------------- public class Shop : Company { public Shop(string shopid) : base(shopid) { } public override void AddShop(Company shop) { Console.WriteLine("暂无下级"); } public override void DisplayShops() { throw new NotImplementedException(); } public override void RemoveShop(Company shop) { Console.WriteLine("暂无下级"); } }
2.3 客户端
//---------------------组合模式------------------------ Component.Company baseShop = new Component.Headquarters("华北区"); baseShop.AddShop(baseShop); Component.Company shop_1 = new Component.Shop("加盟店:NO.1"); baseShop.AddShop(shop_1); Component.Company shop_2 = new Component.Shop("加盟店:NO.2"); baseShop.AddShop(shop_2); baseShop.DisplayShops(); Console.ReadKey();
结果:
三、总结
需求中有部分和整体的关系,并且部分和整体的表达近乎一致。就可考虑使用组合模式。
标签:
原文地址:http://www.cnblogs.com/sunchong/p/5131309.html