C#装饰者模式实例分析

内容摘要
本文实例讲述了C#装饰者模式。分享给大家供大家参考。具体方法如下:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespac
文章正文

本文实例讲述了C#装饰者模式。分享给大家供大家参考。具体方法如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 装饰者
{
  class Program
  {
    static void Main(string[] args)
    {
      ConcreteComponent con = new ConcreteComponent();
      ConcreteDecoratorA a = new ConcreteDecoratorA();
      a.SetComponent(con);
      a.Operation();
      a.AddBehavior();
      Console.WriteLine("============================");
      ConcreteDecoratorB B = new ConcreteDecoratorB();
      B.SetComponent(a);
      a.AddBehavior();
      B.Operation();
      B.AddBehavior();
    }
    public abstract class Component
    {
      public abstract void Operation();
    }
    abstract class Decorator : Component
    {
      private Component component;
      public void SetComponent(Component component)
      {
        this.component = component;
      }
      public override void Operation()
      {
        if (component != null)
        {
          component.Operation();
        }
      }
    }
    class ConcreteDecoratorA : Decorator
    {
      public override void Operation()
      {
        base.Operation();
      }
      public void AddBehavior()
      {
        Console.WriteLine("装饰A类的操作!");
      }
    }
    class ConcreteDecoratorB : Decorator
    {
      public override void Operation()
      {
        base.Operation();
      }
      public void AddBehavior()
      {
        Console.WriteLine("装饰B类的操作!");
      }
    }
    public class ConcreteComponent : Component
    {
      public override void Operation()
      {
        Console.WriteLine("具体对象的操作!");
      }
    }
  }
}

希望本文所述对大家的C#程序设计有所帮助。


代码注释

作者:喵哥笔记

IDC笔记

学的不仅是技术,更是梦想!