裝飾模式(Decorator),動態(tài)地給一個對象添加一些額外的職責,就增加功能來說,裝飾模式比生成子類更為靈活。[DP]

image.png
//Component類
abstract class Component {
public abstract void Operation();
}
//ConcrenteComponent類
class ConcrenteComponent : Component
{
public override void Operation()
{
//具體對象操作
}
}
//Decorator類
abstract class Decorator : Component
{
Component component;
public void SetComponent(Component component)
{
this.component = component;
}
public override void Operation()
{
if (component != null)
{
component.Operation();
}
}
}
//客戶端代碼
class TestDecorator : MonoBehaviour {
void Start () {
ConcrenteComponent c = new ConcrenteComponent();
ConcreteDecoratorA cd1 = new ConcreteDecoratorA();
ConcreteDecoratorB cd2 = new ConcreteDecoratorB();
cd1.SetComponent(c);
cd2.SetComponent(cd1);
cd2.Operation();
}
}
總結:裝飾模式簡化原有的類。把類與裝飾功能區(qū)分開了,這樣可以有效使用裝飾功能,自由度也變得很高。
何時使用:當一個功能新加入的東西僅僅是為了滿足一些只在某種特定情況下才會執(zhí)行的特殊行為。裝飾模式把裝飾的功能放在單獨的類中,并讓這個類包裝它所要裝飾的對象,當需要執(zhí)行特殊行為時,按選擇順序使用裝飾功能包裝對象。