装饰模式

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

装饰模式的UML图:

具体的一个小例子的UML图:

 

相应的代码是:

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

namespace 装饰模式
{
    class Program
    {
        static void Main(string[] args)
        {

            Person xc = new Person("小菜");
            Console.WriteLine("\n 第一种装扮:");

            Sneakers pqx =new Sneakers ();
            TShirts dtx = new TShirts();
            BigTouser kk = new BigTouser();
            
            pqx .Decorate (xc );
            dtx.Decorate(pqx );
            kk.Decorate(dtx );
            kk.Show();
      }
    }
    class Person
    {
        public Person ()
        { }
        private string name;
        public Person (string name )
        {
            this.name = name;
        }
        public virtual void Show()
        {
            Console.WriteLine("装扮的{0}", name);
        }
    }
    class Finery :Person
    {
        protected Person compenent;
        public void Decorate(Person compenent)
        {
            this.compenent = compenent;
        }
        public override void Show()
        {
           if (compenent  != null)
            {
                compenent .Show();
            }
        }
       
    }
    class TShirts : Finery
    {
        public override void Show()
        {
             Console.Write("大T恤 ");
            base.Show();
           
        }
    }
    class BigTouser:Finery
    {
        public override void Show()
        {
           Console.Write("垮裤 ");
            base.Show();
           
        }
    }
    class  Sneakers : Finery
    {
         public override void Show()
        {
           Console.Write("破球鞋 ");
            base.Show();
    }
    }
    class suit:Finery 
    {
         public override void Show()
        {
           Console.Write("西装 ");
            base.Show();
    }
    }
        class Tie:Finery 
        {
             public override void Show()
        {
           Console.Write("领带 ");
            base.Show();
        }
        }
        class LeathShoes : Finery
        {
            public override void Show()
            {
                Console.Write("皮鞋 ");
                base.Show();
            }
        }
}


 

在这个小例子中,两个的UML图并不一致,这就是所谓的变通了。如果只有一个ConcreteComponent类而没有抽象的Component类,那么Decorator类就可以是ConcreteComponent的一个子类。同样的道理,如果只有一个ConcreteDecorate类,那么就没有必要建立一个单独的Decorator类,而可以把Decorator和ConcreteDecorator的责任合并成一个类。

装饰模式是为已有功能动态的添加更多的新功能的时候,是向旧的类中添加新的代码,这些新的代码通常装饰了原有类的核心职责或主要行为。

装饰模式有效地把累的核心职责和装饰功能区分开来,而且可以去除相关中复杂的装饰逻辑。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值