参考于:
《设计模式Head First》
装饰模式:动态的将责任附加到对象上。若要扩展功能,一般这是个比继承更有弹性的替代方案。
设计原则1:类应该对扩展开放,对修改关闭。
1、装饰模式原型
装饰模式原型UML
装饰模式原型代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DecorateMode : MonoBehaviour
{
private void Start () {
ICoffee coffee1 = new LightCoffee();
Debug.Log("咖啡容量:" + coffee1.Capacity() + "咖啡价格:" + coffee1.Cost());
coffee1 = coffee1.AddDecorate(new MilkDecorate());
Debug.Log("添加牛奶后咖啡容量:" + coffee1.Capacity() + "咖啡价格:" + coffee1.Cost());
coffee1 = coffee1.AddDecorate(new PearlDecorate());
Debug.Log("添加珍珠后咖啡容量:" + coffee1.Capacity() + "咖啡价格:" + coffee1.Cost());
}
}
/// <summary>
/// 咖啡
/// </summary>
public abstract class ICoffee
{
//咖啡的容量和消费
public abstract double Capacity();
public abstract double Cost();
/// <summary>
/// 给咖啡添加调料,会改变咖啡
/// </summary>
public ICoffee AddDecorate(DecorateCoffee decorate)
{
decorate.Coffee = this;
return decorate;
}
}
//淡咖啡和浓咖啡
public class LightCoffee : ICoffee
{
public override double Capacity()
{
return 100;
}
public override double Cost()
{
return 20;
}
}
public class StrongCoffee : ICoffee
{
public override double Capacity()
{
return 150;
}
public override double Cost()
{
return 15;
}
}
/// <summary>
/// 装饰咖啡类
/// </summary>
public class DecorateCoffee : ICoffee
{
/// <summary>
/// 要装饰的咖啡对象
/// </summary>
protected ICoffee mCoffee;
public ICoffee Coffee { set { mCoffee = value; } }
public override double Capacity()
{
return mCoffee.Capacity();
}
public override double Cost()
{
return mCoffee.Cost();
}
}
/// <summary>
/// 添加牛奶。容量+20,价格+3。
/// </summary>
public class MilkDecorate : DecorateCoffee
{
public override double Capacity()
{
return mCoffee.Capacity() + 20;
}
public override double Cost()
{
return mCoffee.Cost() + 3;
}
}
/// <summary>
/// 添加珍珠。容量+10,价格+2。
/// </summary>
public class PearlDecorate : DecorateCoffee
{
public override double Capacity()
{
return mCoffee.Capacity() + 10;
}
public override double Cost()
{
return mCoffee.Cost() + 2;
}
}
结果
2、装饰模式优缺点
优点
- 扩展性高,灵活性强。
缺点
- 装饰模式中有大量的小类,会导致类的数量较多。
- 某些情况下导入装饰者,可能会出现一些状况。