程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> Design patterns IV : Decorator/Wrapper Pattern

Design patterns IV : Decorator/Wrapper Pattern

編輯:C++入門知識

/*

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

 


 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved