码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式 -- 装饰器

时间:2019-09-13 15:48:40      阅读:58      评论:0      收藏:0      [点我收藏+]

标签:override   rcu   stp   cte   where   ret   return   void   rhel   

装饰器模式的核心是有继承有组合,继承和组合的抽象类还是一个!

用起来就是一层层的嵌套:

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();

 

设计模式 -- 装饰器

标签:override   rcu   stp   cte   where   ret   return   void   rhel   

原文地址:https://www.cnblogs.com/qgbo/p/11516662.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!