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

今天俺要说一说装饰着模式(Decorator)

时间:2018-09-02 16:11:45      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:职责   今天   round   stand   code   run   结构   ace   一个   

前言:装饰者模式,又叫做装饰器模式.顾名思义,就是给对象包裹一层,包装。让它变成你喜欢的对象。这种模式在我们开发中经常会用到,它是一种处理问题的技巧,即不让程序死板,也可以扩展程序。

(一)何时能用到它》》》

  1.需要给类一个扩展,或者给类附加一个职责。

  2.动态的给类添加一个功能,这些功能可以动态得撤销。

  3.当不能采用子类进行扩展的时候。

这一文中,我们以主要的3来举例说明的。

(二)装饰器的结构图》》》

技术分享图片

 

IAction:装饰器标准接口,装有装饰器都要实现它。

DelegateAction:装饰类,用来实现IAction插口的功能,并对外部提供另一种表现形式。

StandardAction:标准实现类,用来实现IAction插口的功能,对其展示也是以IAction接口为准的

Implement:对外公开的调用类,它向外部公开两种接口方法,一是IAction接口标准,一是Action<int> 委托标准。

装饰器的C#实现

 IAction.cs

 

#region 装饰着模式
    public interface IAction
    {
        void Pring(int a);
    }
    #endregion

 

DelegateAction.cs

public class DelegateAction:IAction
    {
        Action<int> _action;
        public void Pring(int a)
        {
            _action(a);
        }
        public DelegateAction(Action<int> action)
        {
            _action = action;
        }
    }

Implement.cs

 public class Implement
    {
        public void Run(IAction action)
        {
            action.Pring(10);
        }
        public void Run(Action<int> action)
        {
            new DelegateAction(action).Pring(10);
        }
    }

standarAction.cs

public class standarAction : IAction
    {
        public void Pring(int a)
        {
            Console.Write("标准实现装饰器"+a);
        }
    }

调用:

 static void Main(string[] args)
        {
            Implement implement = new Implement();
            implement.Run((a) => Console.Write(a));
            implement.Run(new standarAction());
        }

 

今天俺要说一说装饰着模式(Decorator)

标签:职责   今天   round   stand   code   run   结构   ace   一个   

原文地址:https://www.cnblogs.com/ZaraNet/p/9573885.html

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