设计模式组合模式
Posted talentzemin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式组合模式相关的知识,希望对你有一定的参考价值。
模式介绍
组合模式使得用户对单个对象和组合对象的使用具有一致性。
示例
我们使用一个汽水售卖机进行建模,这玩意会先让你选择品牌(可乐、芬达、雪碧),然后让你选择口味(樱桃味、香草味)。
定义饮料类
/// <summary>
/// Component abstract class
/// </summary>
public abstract class SoftDrink
{
public int Calories { get; set; }
public List<SoftDrink> Flavors { get; set; }
public SoftDrink(int calories)
{
Calories = calories;
Flavors = new List<SoftDrink>();
}
/// <summary>
/// "Flatten" method, returns all available flavors
/// </summary>
public void DisplayCalories()
{
Console.WriteLine(this.GetType().Name + ": " + this.Calories.ToString() + " calories.");
foreach (var drink in this.Flavors)
{
drink.DisplayCalories();
}
}
}
创建不同口味的不同饮料,可乐(2)、生啤(2)、柠檬汁(1)
/// <summary>
/// Leaf class
/// </summary>
public class VanillaCola : SoftDrink
{
public VanillaCola(int calories) : base(calories) { }
}
/// <summary>
/// Leaf class
/// </summary>
public class CherryCola : SoftDrink
{
public CherryCola(int calories) : base(calories) { }
}
/// <summary>
/// Leaf class
/// </summary>
public class StrawberryRootBeer : SoftDrink
{
public StrawberryRootBeer(int calories) : base(calories) { }
}
/// <summary>
/// Leaf class
/// </summary>
public class VanillaRootBeer : SoftDrink
{
public VanillaRootBeer(int calories) : base(calories) { }
}
/// <summary>
/// Leaf class
/// </summary>
public class LemonLime : SoftDrink
{
public LemonLime(int calories) : base(calories) { }
}
组合类
/// <summary>
/// Composite class
/// </summary>
public class Cola : SoftDrink
{
public Cola(int calories) : base(calories) { }
}
/// <summary>
/// Composite class
/// </summary>
public class RootBeer : SoftDrink
{
public RootBeer(int calories) : base(calories) { }
}
组合类,根节点
/// <summary>
/// Composite class, root node
/// </summary>
public class SodaWater : SoftDrink
{
public SodaWater(int calories) : base(calories) { }
}
客户端调用:
static void Main(string[] args)
{
var colas = new Cola(210);
colas.Flavors.Add(new VanillaCola(215));
colas.Flavors.Add(new CherryCola(210));
var lemonLime = new LemonLime(185);
var rootBeers = new RootBeer(195);
rootBeers.Flavors.Add(new VanillaRootBeer(200));
rootBeers.Flavors.Add(new StrawberryRootBeer(200));
SodaWater sodaWater = new SodaWater(180);
sodaWater.Flavors.Add(colas);
sodaWater.Flavors.Add(lemonLime);
sodaWater.Flavors.Add(rootBeers);
sodaWater.DisplayCalories();
Console.ReadKey();
}
总结
组合模式可以“扁平化”所有或部分层次结构
源代码
https://github.com/exceptionnotfound/DesignPatterns/tree/master/Composite
原文
https://www.exceptionnotfound.net/composite-the-daily-design-pattern/
以上是关于设计模式组合模式的主要内容,如果未能解决你的问题,请参考以下文章