设计模式 -- 装饰器
Posted qgbo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式 -- 装饰器相关的知识,希望对你有一定的参考价值。
装饰器模式的核心是有继承有组合,继承和组合的抽象类还是一个!
用起来就是一层层的嵌套:
BaseCharacter character = new Mage(); character = new BaseDecorator(character);// character = new DecoratorHelmet(character);// character = new DecoratorShoulder(character);// character = new DecoratorBreastplate(caracter); character = new DecoratorCuish(character); character = new DecoratorGlove(character);
能不能链式写呢?
public class BaseDecorator : BaseCharacter private BaseCharacter _BaseCharacter = null; public BaseDecorator(BaseCharacter character) this._BaseCharacter = character; public override void Show() this._BaseCharacter.Show(); public BaseDecorator Decorat<T>() where T : BaseDecorator return (T)Activator.CreateInstance(typeof(T), new object[] this);
这样就可以链式了!
BaseCharacter character = new Mage(); character = new BaseDecorator(character).Decorat<DecoratorHelmet>().Decorat<DecoratorCuish>();// character.Show();
以上是关于设计模式 -- 装饰器的主要内容,如果未能解决你的问题,请参考以下文章