装饰器模式(Decorator Pattern)
允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。
对客户端透明的方式扩展对象的功能,继承关系的替代方案。
场景:
1.需要扩展一个类的功能
2.需要动态的给一个对象增加功能,也可以动态的撤销
3.需要增加大量排列组合的功能,继承关系不现实
优点:
- 装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。
- 比继承关系灵活,可以在运行时动态增加或取消功能。
- 可以排列组合实现新功能,不需要多种组合建立大量的继承类。
缺点:
- 多层装饰比较复杂。
- 对象嵌套,灵活性强,意味着更容易出错,不易排除错误。
抽象杯子类:
/// <summary>
/// 抽象类:杯子
/// </summary>
public abstract class Ab_Cup
{
public abstract string Print();
}
具体杯子类:
/// <summary>
/// 具体类
/// </summary>
public class Cup : Ab_Cup
{
public override string Print()
{
return "我有个杯子 ";
}
}
抽象装饰类:
/// <summary>
/// 抽象装饰类
/// </summary>
public abstract class Ab_Decorator : Ab_Cup
{
private Ab_Cup cup; //该装饰对象装饰到的cup组件实体对象
public Ab_Decorator(Ab_Cup cup)//构造函数 添加被装饰物
{
this.cup = cup;
}
public override string Print()//重写原功能类
{
return cup.Print();
}
}
具体装饰类:咖啡
/// <summary>
/// 具体装饰:咖啡
/// </summary>
public class Coffee : Ab_Decorator
{
public Coffee(Ab_Cup cup) : base(cup) { }
public override string Print()//重写原功能类 添加新装饰功能
{
return base.Print() + AddCoffee();
}
public string AddCoffee()//新功能
{
return "倒入咖啡 ";
}
}
具体装饰类:牛奶
/// <summary>
/// 具体装饰:牛奶
/// </summary>
public class Milk : Ab_Decorator
{
public Milk(Ab_Cup cup) : base(cup) { }
public override string Print()//重写原功能类 添加新装饰功能
{
return base.Print() + AddMilk();
}
public string AddMilk()//新功能
{
return "倒入牛奶 ";
}
}
具体装饰类:方糖
/// <summary>
/// 具体装饰:方糖
/// </summary>
public class Sugar : Ab_Decorator
{
public Sugar(Ab_Cup cup) : base(cup) { }
public override string Print()//重写原功能类 添加新装饰功能
{
return base.Print() + AddSugar();
}
public string AddSugar()//新功能
{
return "加入方糖 ";
}
}
运行测试:
void Start()
{
Ab_Cup cup = new Cup(); //新建一个杯子
Ab_Decorator Cup_Coffee = new Coffee(cup); //新建一个装饰类:咖啡 ,倒入杯子
Debug.Log(Cup_Coffee.Print()); //打印结果
Debug.Log("==========================");
Ab_Decorator Cup_Milk = new Milk(cup); //新建一个装饰类:牛奶 ,倒入杯子
Debug.Log(Cup_Milk.Print()); //打印结果
Debug.Log("==========================");
Cup_Coffee = new Coffee(cup); //咖啡倒入杯子
Cup_Milk = new Milk(Cup_Coffee); //牛奶倒入盛了咖啡的杯子
Ab_Decorator Cup_Sugar = new Sugar(Cup_Milk); //接着加入方糖
Debug.Log(Cup_Sugar.Print()); //打印结果
}
结果: