设计模式之装饰模式

一:装饰模式的概念

1、装饰模式(Decorator),动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生产子类更为灵活

2、装饰模式是为已有的功能动态添加更多功能的一种方式,把每个要装饰的功能放在单独的类中,并让这个类包装所要装饰的对象,因此,当需要执行特殊行为的时候,客户代码就可以再运行时进行装饰

2、装饰模式结构图

 

二、实例

1、代码结构视图

2、相关代码

“Person”类(ConcreteComponent)

 public class Person
    {
        public Person()
        {
        }

        private string name;

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

        public virtual void Show()
        {
            Console.WriteLine("装扮的{0}",name);
        }
    }

 "服饰类"(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();
            }
        }

    }

 具体服饰类(ConcreteDecorator)

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

 

  public   class WearLeatherShoes:Finery//皮鞋
    {
        public override void Show()
        {
            Console.Write("皮鞋");
            base.Show();
        }
    }

 

public  class WearTie:Finery//领带
    {
         public override void Show()
         {
             Console.Write("领带");
             base.Show();
         }
    }
}
 

 

 public   class WearSuita:Finery//西装
    {
        public override void Show()
        {
            Console.Write("西装");
            base.Show();
        }
    }
  

 

public class BigTrouser : Finery//垮裤
    {
        public override void Show()
        {
           Console.Write("垮裤");
            base.Show();
        }
    }

 

 客户代码

   class Program
    {
        static void Main(string[] args)
        {
            Person xc = new Person("小菜");
            Console.WriteLine("\n第一种装扮");
            WearSneakers pqx=new WearSneakers();
            BigTrouser kk=new BigTrouser();
            TShirts dtx=new TShirts();

            pqx.Decorate(xc);//装饰过程
            kk.Decorate(pqx);
            dtx.Decorate(kk);
            dtx.Show();

            Console.WriteLine("\n第二种装扮");
            WearLeatherShoes px=new WearLeatherShoes();
            WearTie ld=new WearTie();
            WearSuita xz=new WearSuita();

            px.Decorate(xc);//装饰过程
            ld.Decorate(px);
            xz.Decorate(ld);
            xz.Show();

            Console.Read();
        }
    }

 运行结果

posted @ 2017-02-24 23:03  忘-语  阅读(155)  评论(0编辑  收藏  举报