設計模式c#描述——裝飾(Decorator)模
發表時間:2024-02-18 來源:明輝站整理相關軟件相關文章人氣:
[摘要]設計模式c#語言描述——裝飾(Decorator)模式 *本文參考了《JAVA與模式》的部分內容,適合于設計模式的初學者。 裝飾模式又名包裝模式,以對客戶端透明的方式擴展對象的功能,是繼承關系的一個替代方案。它使用原來被裝飾的類的一個子類的實例,把客戶端的調用委派到被裝飾類,客戶端并不會覺得對象在...
設計模式c#語言描述——裝飾(Decorator)模式
*本文參考了《JAVA與模式》的部分內容,適合于設計模式的初學者。
裝飾模式又名包裝模式,以對客戶端透明的方式擴展對象的功能,是繼承關系的一個替代方案。它使用原來被裝飾的類的一個子類的實例,把客戶端的調用委派到被裝飾類,客戶端并不會覺得對象在裝飾前和裝飾后有什么不同。在以下情況下應使用裝飾模式:需要擴展一個類的功能,或給一個類增加附加責任。動態地給一個對象增加功能,這些功能可以再動態地撤銷。需要增加由一些基本功能的排列組合而產生的非常大量的功能,從而使繼承關系變得不現實。
類圖如下所示:
裝飾模式包括如下角色:
抽象構件(Component):給出一個抽象接口,以規范準備接收附加責任的對象。
具體構件(Concrete Component):定義一個將要接收附加責任的類。
裝飾(Decorator):持有一個構件對象的實例,并定義一個與抽象構件接口一致的接口。
具體裝飾(Concrete Decorator):負責給構件對象“貼上”附加的責任。
Component:
public interface Component
{
void sampleOperation();
}// END INTERFACE DEFINITION Component
Decorator:
public class Decorator : Component
{
private Component component;
public Decorator(Component component)
{
this.component=component;
}
public virtual void sampleOperation()
{
component.sampleOperation();
}
}// END CLASS DEFINITION Decorator
ConcreteComponent:
public class ConcreteComponent : Component
{
public void sampleOperation()
{
Console.WriteLine ("ConcreteComponent sampleOperation");
}
}// END CLASS DEFINITION ConcreteComponent
ConcreteDecorator1:
public class ConcreteDecorator1 : Decorator
{
public ConcreteDecorator1(Component component):base(component)
{
}
override public void sampleOperation()
{
base.sampleOperation ();
Console.WriteLine ("ConcreteDecorator1 sampleOperation");
}
}// END CLASS DEFINITION ConcreteDecorator1
ConcreteDecorator2:
public class ConcreteDecorator2 : Decorator
{
public ConcreteDecorator2 (Component component):base(component)
{
}
override public void sampleOperation()
{
base.sampleOperation ();
Console.WriteLine ("ConcreteDecorator2 sampleOperation");
}
}// END CLASS DEFINITION ConcreteDecorator2
Client:
static void Main(string[] args)
{
Component component=new ConcreteComponent ();
Component concretedecorator1=new ConcreteDecorator1 (component); // 包裝
Component concretedecorator2=new ConcreteDecorator2 (concretedecorator1);
concretedecorator2.sampleOperation ();
}
程序輸出如下:
ConcreteComponent sampleOperation
ConcreteDecorator1 sampleOperation
ConcreteDecorator2 sampleOperation