《大话设计模式》学习笔记3:装饰模式

  

  

穿衣服示例:

  

1.ConcreteComponent(人类):

    public class Person
    {
        public virtual void Show()
        {
            Console.Write("开始装扮:");
        }
    }

2.Decorator(服饰类):

    public class Finery:Person
    {
        protected Person component;
        public void Decorate(Person component)
        {
            this.component = component;
        }
        public override void Show()
        {
            if(component!=null)
            {
                component.Show();
            }
        }
    }

3.ConcreteDecorator(具体服饰类,以垮裤类为例):

    public class BigTrouser:Finery
    {
        public override void Show()
        {
            base.Show();//首先运行原Component的操作,再执行本类的操作
            Console.Write("垮裤 ");
        }
    }

4.客户端代码:

    class Program
    {
        static void Main(string[] args)
        {
            Person person = new Person();
            BigTrouser bigTrouser = new BigTrouser();
            TShirts tShirts = new TShirts(); 
            LeatherShoes leatherShoes = new LeatherShoes();

            bigTrouser.Decorate(person);
            tShirts.Decorate(bigTrouser);
            leatherShoes.Decorate(tShirts);

            leatherShoes.Show();
        }
    }

  如果只有一个ConcreteComponent类而没有抽象的Component类,那么Decorator类可以是ConcreteComponent的一个子类。同样道理,如果只有一个ConcreteDecorator类,那就没有必要建立一个单独的Decorator类,而可以把Decorator和ConcreteDecorator的责任合并成一个类。

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

  优点:有效地把类的核心职责和装饰功能区分开,而且可以去除相关类中重复的逻辑。

原文地址:https://www.cnblogs.com/walden1024/p/4487741.html