Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

Design patterns IV : Decorator/Wrapper Pattern

$
0
0

/*

Author: Jiangong SUN

*/

Decorators provide a flexible alternative to subclassing for extending functionality.

public class DecoratorPattern
    {
         /*
         * decorator和wrapper是一个设计模式
         * 用途:用来扩展已有类的功能
         * 实现步骤:
         * 先定义一个interface,然后建立一个类继承这个接口,并实现接口里的方法
         * 建立一个包装类继承同一个接口,并在这个包装类的构造器中使用接口的实例做参数。
         * 建立实际包装类继承包装类,重写接口定义的方法,并可以创建自己特有的方法。
         */
        public interface IComponent
        {
            void Operation();
        }

        public class ConcreteComponent : IComponent
        {
            public void Operation()
            {
                Console.WriteLine("ConcreteComponent operation");
            }
        }

        public class Decorator : IComponent
        {
            private readonly IComponent _decoratedComponent;

            public Decorator(IComponent iComponent)
            {
                _decoratedComponent = iComponent;
            }

            public void Operation()
            {
                _decoratedComponent.Operation();
            }
        }

        public class ConcreteDecoratorA : Decorator
        {
            private string _addState;

            public ConcreteDecoratorA(Decorator decorator)
                : base(decorator)
            {
            }

            public new void Operation()
            {
                base.Operation();
                _addState = "New State";
                Console.WriteLine("ConcreteDecoratorA.Operation");
            }
            public void CustomOperation()
            {
                Console.WriteLine("ConcreteDecoratorA custom Operation");
            }
        }

        public static void Main()
        {
            ConcreteComponent concreteComponent = new ConcreteComponent();
            concreteComponent.Operation();

            Decorator decorator = new Decorator(concreteComponent);
            ConcreteDecoratorA concreteDecoratorA = new ConcreteDecoratorA(decorator);
            concreteDecoratorA.Operation();
            concreteDecoratorA.CustomOperation();

            Console.ReadKey();
        }
    }



reference:

http://en.wikipedia.org/wiki/Decorator_pattern

http://geekswithblogs.net/amaniar/archive/2012/02/10/a-simple-implementation-of-the-decorator-design-pattern-using-c-sharp.aspx

http://sourcemaking.com/design_patterns/decorator/c%2523

作者:garcon1986 发表于2013-6-8 1:55:18 原文链接
阅读:124 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>