设计模式之装饰模式

装饰模式是为已有功能动态地添加更多功能的一种方式。

         当系统需要新功能的时候,是向旧的类中添加新的代码。这些新加的代码通常装饰了原有类的核心职责或主要行为,在主类中加入了新的字段,新的方法和新的逻辑,从而增加了主类的复杂度,而这些新加入的东西仅仅是为了满足一些只在某种特定情况下才会执行的特殊行为的需要。装饰模式提供了一个非常好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类包装它所需要装饰的对象,因此,当需要执行特性行为时,客户代码就可以在运行时根据需要有选择地、按顺序地使用装饰功能包装对象了。

以一个衣着打扮为例子:

首先创建一个装扮者的类:

class Person
{
      private string _name;
      public Person()
      {
      }

      public Person(string name)
      {
          this._name = name;
      }

      public virtual void Show()
      {
          Console.WriteLine("{0}今天的装扮:", _name);
      }
}

再创建一个装饰类,继承自装扮者的类:

class Finery:Person
{
    protected Person component;
    public void Decorate(Person person)
     {
         this.component = person;
     }

     public override void Show()
     {
         if (this.component!=null)
         {
             this.component.Show();
         }
     }
}

最后创建几个装饰,继承自装饰类,例如:T恤、牛仔裤、运动鞋等等:

T恤类:

class TShirt:Finery
{
    public override void Show()
    {
        base.Show();
        Console.Write("T恤 ");
            
    }
}

牛仔裤类:

class Jeans:Finery
{
    public override void Show()
    {
        base.Show();
        Console.Write("牛仔裤 ");
    }
}

运动鞋类:

class Sneaker:Finery
{
   public override void Show()
   {
        base.Show();
        Console.Write("运动鞋 ");
    }
}

Program类:

static void Main(string[] args)
{
    Person person = new Person("小白");
    Console.WriteLine("今天的打扮:");
    TShirt shirt = new TShirt();
    Jeans jeans = new Jeans();
    Sneaker sneaker = new Sneaker();
    shirt.Decorate(person);
    jeans.Decorate(shirt);
    sneaker.Decorate(jeans);
    sneaker.Show();
}

执行的结果为:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值