您的位置:首页 > 科技 > 能源 > C# 装饰器模式(Decorator Pattern)

C# 装饰器模式(Decorator Pattern)

2024/10/5 19:18:10 来源:https://blog.csdn.net/u010992421/article/details/140314287  浏览:    关键词:C# 装饰器模式(Decorator Pattern)

装饰器模式动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活。

// 组件接口  
public interface IComponent  
{  void Operation();  
}  // 具体组件  
public class ConcreteComponent : IComponent  
{  public void Operation()  {  Console.WriteLine("ConcreteComponent.Operation()");  }  
}  // 装饰器抽象类  
public abstract class Decorator : IComponent  
{  protected IComponent _component;  public Decorator(IComponent component)  {  _component = component;  }  public virtual void Operation()  {  _component.Operation();  }  
}  // 具体装饰器  
public class ConcreteDecoratorA : Decorator  
{  public ConcreteDecoratorA(IComponent component) : base(component) {}  public override void Operation()  {  base.Operation();  AddedFunctionality();  }  private void AddedFunctionality()  {  Console.WriteLine("Added functionality in ConcreteDecoratorA");  }  
}  // 客户端代码  
class Program  
{  static void Main(string[] args)  {  IComponent component = new ConcreteComponent();  // 装饰者模式的使用  component = new ConcreteDecoratorA(component);  // 执行操作  component.Operation();  }  
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com