美文网首页设计模式
设计模式 - 装饰模式

设计模式 - 装饰模式

作者: Mitchell | 来源:发表于2016-01-25 19:52 被阅读59次
  • 装饰模式是为已有功能动态的添加更多功能的一种方式。
  • 当系统需要新功能的时候,是向旧的类中添加新的代码,这些代码通常装饰了原有类的核心职责或者主要行为。
  • 装饰模式的有点,把类中的装饰功能从类中搬移去除,这样可以简化原有的类。
  • 有效的把类的核心职责和装饰功能区分开了,而且可以去除相关类中重复的装饰逻辑。
  • 举例
using System;
namespace Factory1
{
    //人
    class Person{
        public Person(){}
        private string name;
        public Person(string name)
        {
            this.name = name;
        }
        public virtual void Show()
        {
            Console.WriteLine ("\nresult = {0}", name);
        }
    }
    //装饰 人
    class Finery:Person{
        protected Person component;
        public void Decorate(Person component)
        {
            this.component = component;
        }
        public override void Show()
        {
            if (component != null) {
                component.Show ();
            }
        }
    }
    //装饰 人 + Tshirt
    class TShirts:Finery{
        public override void Show()
        {
            Console.Write ("T-Shirt");
            base.Show ();
        }
    }
    //装饰 人 + BigTrouser
    class BigTrouser:Finery{
        public override void Show(){
            Console.Write("BigTrouser");
            base.Show ();
        }
    }
    class MainClass
    {
        public static void Main (string[] args)
        {
            Person sc = new Person ("little");
            Console.WriteLine ("the First category");
            TShirts ts = new TShirts ();
            BigTrouser bt = new BigTrouser ();
            ts.Decorate (sc);
            bt.Decorate (ts);
            bt.Show ();
            Console.Read ();
        }
    }
}

相关文章

网友评论

    本文标题:设计模式 - 装饰模式

    本文链接:https://www.haomeiwen.com/subject/ijcdkttx.html