public Client() { Component component = new ConcreateComponent(); component = new ConcreateDecoratorA(component); component = new ConcreateDecoratorB(component); component.Operation(); }
public void TestMethod1() { var component = new ConcreteComponent(); var decoratorA = new ConcreateDecoratorA(); var decoratorB = new ConcreateDecoratorB(); decoratorA.SetComponent(component); decoratorB.SetComponent(decoratorA); decoratorB.Operation(); }
// Start is called before the first frame update void Start() { //装饰模式 ConcreateMyComponent behavior = new ConcreateMyComponent(); // MyDecorator myDecorator = new MyDecorator(); //错误的,抽象类不能实例化 //MyDecorator myDecorator = new ConcreateDecoratorA(); //正确的 这叫多态的向上转型,基类引用指向派生类的实际对象new后面跟哪个类就是哪个类的对象。 ConcreateMyComponent c = new ConcreateMyComponent(); ConcreateDecoratorA d1 = new ConcreateDecoratorA(); ConcreateDecoratorB d2 = new ConcreateDecoratorB(); d1.SetMyComponent(c); /*装饰的方式是 : 首先用concreateMyComponent实例化对象c, 然后用d1包装c, 再用d2包装d1 * 装饰模式是利用setcomponent 来对对象进行包装的, 这样每个装饰对象的实现就和如何利用这个对象分离开了, 每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链中*/ d2.SetMyComponent(d1); d2.Operation(); }
/// <summary> /// (1)需要扩展一个类的功能、或者给一个类添加附加的职责时。 /// (2)需要动态的给一个对象添加功能,这些功能可以再动态的撤销时。 /// (3)需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变得不现实。 /// (4)当不能采用生成子类的方式进行扩充时。 /// </summary> /// <param name="args"></param> static void Main(string[] args) { IComponent component = new ConcreateComponent("XiaoMing"); ConcreateDecoratorA decoratorA = new ConcreateDecoratorA(); decoratorA.decorator(component); ConcreateDecoratorB decoratorB = new ConcreateDecoratorB(); decoratorB.decorator(decoratorA); decoratorB.Show("test"); //IComponent component = new ConcreateDecoratorA(new ConcreateComponent("XiaoMing")); //ConcreateDecoratorA decoratorA = new ConcreateDecoratorA(); //decoratorA.SetComponent(component); component.Show("decorator demo."); Console.ReadLine(); }
static void Main(string[] args) { //装饰者 ConcreateComponent c = new ConcreateComponent(); ConcreateDecoratorA ca = new ConcreateDecoratorA(); ConcreateDecoratorB cb = new ConcreateDecoratorB(); ca.SetComponent(c); cb.SetComponent(ca); cb.Operation(); Console.WriteLine("----------------------------------\r\n"); Person.Person person = new Person.Person("微软"); Person.BigTrouser bt = new Person.BigTrouser(); Person.TShirts ts = new Person.TShirts(); bt.Decorate(person); ts.Decorate(bt); ts.Show(); Console.Read(); }