定義
裝飾器模式(Decorator Pattern):動態(tài)地給一個對象添加一些額外的職責(zé)。就增加功能來說,裝飾器模式相比生成子類更為靈活
允許向一個現(xiàn)有的對象添加新的功能,同時又不改變其結(jié)構(gòu)。這種類型的設(shè)計模式屬于結(jié)構(gòu)型模式,它是作為現(xiàn)有的類的一個包裝。
這種模式創(chuàng)建了一個裝飾類,用來包裝原有的類,并在保持類方法簽名完整性的前提下,提供了額外的功能。
C#例子
public interface ICommand
{
void Executed();
}
public class CreateOrder : ICommand
{
public void Executed()
{
Console.WriteLine("創(chuàng)建了訂單信息!");
}
}
public class WriteLogDecorator : ICommand
{
private ICommand _command;
public WriteLogDecorator(ICommand command) {
_command = command;
}
public void Executed()
{
Console.WriteLine("記錄了日志!");
_command.Executed();
}
}
public class PayDecorator : ICommand
{
private ICommand _command;
public PayDecorator(ICommand command)
{
_command = command;
}
public void Executed()
{
_command.Executed();
Console.WriteLine("支付了完成了!");
}
}
public class StockDecorator : ICommand
{
private ICommand _command;
public StockDecorator(ICommand command)
{
_command = command;
}
public void Executed()
{
_command.Executed();
Console.WriteLine("扣減了庫存!");
}
}
static void Main(string[] args)
{
// 記錄日志、創(chuàng)建單據(jù)
var cmd1 = new WriteLogDecorator(new CreateOrder());
cmd1.Executed();
// 記錄日志、創(chuàng)建單據(jù)、扣減庫存、支付
var cmd2 = new WriteLogDecorator(new StockDecorator(new PayDecorator(new CreateOrder())));
cmd2.Executed();
Console.ReadLine();
}
裝飾器模式適用情形:
- 在不想增加很多子類的情況下擴(kuò)展一個類的功能
- 動態(tài)增加功能,動態(tài)撤銷
裝飾器模式特點:
- 可代替繼承
- 裝飾類和被裝飾類可以獨立發(fā)展,不會相互耦合,裝飾模式是繼承的一個替代模式,裝飾模式可以動態(tài)擴(kuò)展一個實現(xiàn)類的功能
- 多層裝飾比較復(fù)雜
- 都必須繼承ICommand
其他
源碼地址
其他設(shè)計模式