设计模式学习之路——Decorator装饰模式(结构模式)
子类复子类,子类何其多
假如我们需要为游戏中开发一种坦克,除了各种不同型号的坦克外,我们还希望在不同场合中为其增加以下一种或多种功能:比如红外线夜视功能,比如水陆两栖功能,比如卫星定位功能等等。
动机(Motivation)
上述描述的问题根源在于我们“过度地使用了继承来扩展对象的功能”,由于继承为类型引入的静态特质,使得这种扩展方式缺乏灵活性;并且随着子类的增多(扩展功能的增多),各种子类的组合(扩展功能的组合)会导致更多子类的膨胀(多继承)。如何使“对象功能的扩展”能够根据需要来动态地实现?同时避免“扩展功能的增多”带来的子类膨胀问题?从而使得任何“功能扩展变化”所导致的影响将为最低?
意图(Intent)
动态地给一个对象增加一些额外的职责。就增加功能而言,Decorator模式比生成子类更为灵活。
——《设计模式》GoF
结构(Structure)

代码结构
using System; namespace Decorator.Structural
{
/// <summary>
/// MainApp startup class for Structural
/// Decorator Design Pattern.
/// </summary>
class MainApp
{
static void Main()
{
// Create ConcreteComponent and two Decorators
ConcreteComponent c = new ConcreteComponent();
ConcreteDecoratorA d1 = new ConcreteDecoratorA();
ConcreteDecoratorB d2 = new ConcreteDecoratorB(); // Link decorators
d1.SetComponent(c);
d2.SetComponent(d1); d2.Operation();
// Wait for user
Console.ReadKey();
}
} /// <summary>
/// The 'Component' abstract class
/// </summary>
abstract class Component
{
public abstract void Operation();
} /// <summary>
/// The 'ConcreteComponent' class
/// </summary>
class ConcreteComponent : Component
{
public override void Operation()
{
Console.WriteLine("ConcreteComponent.Operation()");
}
} /// <summary>
/// The 'Decorator' abstract class
/// </summary>
abstract class Decorator : Component
{
protected Component component;
public void SetComponent(Component component)
{
this.component = component;
}
public override void Operation()
{
if (component != null)
{
component.Operation();
}
}
} /// <summary>
/// The 'ConcreteDecoratorA' class
/// </summary>
class ConcreteDecoratorA : Decorator
{
public override void Operation()
{
base.Operation();
Console.WriteLine("ConcreteDecoratorA.Operation()");
}
} /// <summary>
/// The 'ConcreteDecoratorB' class
/// </summary>
class ConcreteDecoratorB : Decorator
{
public override void Operation()
{
base.Operation();
AddedBehavior();
Console.WriteLine("ConcreteDecoratorB.Operation()");
}
void AddedBehavior()
{
}
}
}
输出:

代码示例:
class Program
{
static void Main(string[] args)
{
// Create book
Book book = new Book("Worley", "Inside ASP.NET", 10);
book.Display(); // Create video
Video video = new Video("Spielberg", "Jaws", 23, 92);
video.Display(); // Make video borrowable, then borrow and display
Console.WriteLine("\nMaking video borrowable:"); Borrowable borrowvideo = new Borrowable(video);
borrowvideo.BorrowItem("Customer #1");
borrowvideo.BorrowItem("Customer #2"); borrowvideo.Display(); // Wait for user
Console.ReadKey(); }
} /// <summary>
/// The 'Component' abstract class
/// </summary>
abstract class LibraryItem
{
private int _numCopies; // Property
public int NumCopies
{
get { return _numCopies; }
set { _numCopies = value; }
} public abstract void Display();
} /// <summary>
/// The 'ConcreteComponent' class
/// </summary>
class Book : LibraryItem
{
private string _author;
private string _title; // Constructor
public Book(string author, string title, int numCopies)
{
this._author = author;
this._title = title;
this.NumCopies = numCopies;
} public override void Display()
{
Console.WriteLine("\nBook ------ ");
Console.WriteLine(" Author: {0}", _author);
Console.WriteLine(" Title: {0}", _title);
Console.WriteLine(" # Copies: {0}", NumCopies);
}
} /// <summary>
/// The 'ConcreteComponent' class
/// </summary>
class Video : LibraryItem
{
private string _director;
private string _title;
private int _playTime; // Constructor
public Video(string director, string title,
int numCopies, int playTime)
{
this._director = director;
this._title = title;
this.NumCopies = numCopies;
this._playTime = playTime;
} public override void Display()
{
Console.WriteLine("\nVideo ----- ");
Console.WriteLine(" Director: {0}", _director);
Console.WriteLine(" Title: {0}", _title);
Console.WriteLine(" # Copies: {0}", NumCopies);
Console.WriteLine(" Playtime: {0}\n", _playTime);
}
} /// <summary>
/// The 'Decorator' abstract class
/// </summary>
abstract class Decorator : LibraryItem
{
protected LibraryItem libraryItem; // Constructor
public Decorator(LibraryItem libraryItem)
{
this.libraryItem = libraryItem;
} public override void Display()
{
libraryItem.Display();
}
} /// <summary>
/// The 'ConcreteDecorator' class
/// </summary>
class Borrowable : Decorator
{
protected List<string> borrowers = new List<string>(); // Constructor
public Borrowable(LibraryItem libraryItem)
: base(libraryItem)
{
} public void BorrowItem(string name)
{
borrowers.Add(name);
libraryItem.NumCopies--;
} public void ReturnItem(string name)
{
borrowers.Remove(name);
libraryItem.NumCopies++;
} public override void Display()
{
base.Display(); foreach (string borrower in borrowers)
{
Console.WriteLine(" borrower: " + borrower);
}
}
}
输出:

Decorator模式的几个要点
- 通过采用组合、而非继承的手法, Decorator模式实现了在运行时动态地扩展对象功能的能力,而且可以根据需要扩展多个功能。避免了单独使用继承带来的“灵活性差”和“多子类衍生问题”。
- Component类在Decorator模式中充当抽象接口的角色,不应该去实现具体的行为。而且Decorator类对于Component类应该透明——换言之Component类无需知道Decorator类,Decorator类是从外部来扩展Component类的功能。
- Decorator类在接口上表现为is-a Component的继承关系,即Decorator类继承了Component类所具有的接口。但在实现上又表现为has-a Component的组合关系,即Decorator类又使用了另外一个Component类。我们可以使用一个或者多个Decorator对象来“装饰”一个Component对象,且装饰后的对象仍然是一个Component对象。
- Decorator模式并非解决“多子类衍生的多继承”问题,Decorator模式应用的要点在于解决“主体类在多个方向上的扩展功能”——是为“装饰”的含义。
.NET框架中的Decorator应用

设计模式学习之路——Decorator装饰模式(结构模式)的更多相关文章
- C#设计模式学习笔记:(3)抽象工厂模式
本笔记摘抄自:https://www.cnblogs.com/PatrickLiu/p/7596897.html,记录一下学习过程以备后续查用. 一.引言 接上一篇C#设计模式学习笔记:简单工厂模式( ...
- C#设计模式学习笔记:(2)工厂方法模式
本笔记摘抄自:https://www.cnblogs.com/PatrickLiu/p/7567880.html,记录一下学习过程以备后续查用. 一.引言 接上一篇C#设计模式学习笔记:简单工厂模式( ...
- 设计模式学习之路——Facade 外观模式(结构型模式)
动机: 组件的客户和组件中各种复杂的子系统有了过多的耦合,随着外部客户程序和各子系统的演化,这种过多的耦合面临很多变化的挑战.如何简化外部客户程序和系统间的交互接口?如何将外部客户程序的演化和内部子系 ...
- C#设计模式学习笔记:(8)装饰模式
本笔记摘抄自:https://www.cnblogs.com/PatrickLiu/p/7723225.html,记录一下学习过程以备后续查用. 一.引言 今天我们要讲结构型设计模式的第三个模式--装 ...
- C#设计模式学习笔记:(20)职责链模式
本笔记摘抄自:https://www.cnblogs.com/PatrickLiu/p/8109100.html,记录一下学习过程以备后续查用. 一.引言 今天我们要讲行为型设计模式的第八个模式--职 ...
- javascript设计模式学习之十二——享元模式
一.享元模式的定义及使用场景 享元模式是为了解决性能问题而诞生的设计模式,这和大部分设计模式为了提高程序复用性的原因不太一样,如果系统中因为创建了大量类似对象而导致内存占用过高,享元模式就非常有用了. ...
- 设计模式学习总结(五)创建者模式(Builder)
创建者模式,主要针对某些产品有类似的生产步骤,且有需要有先后顺序的进行各个部件的生成. 一.示例展示: 通过学习及总结,以下是我完成的创建者模式的示例: 1.创建产品类:Laptop public c ...
- 设计模式学习总结(六)原型模式(Prototype)
原型模式即通过对象拷贝的方式来实现对同类对象的生成的一种设计模式! 浅复制:对于值类型,则直接复制该值,对于引用类型的字段则是对其引用的复制,如果原引用与现引用只要有一个的值发生变化,则都会造成两者值 ...
- C#设计模式学习笔记:(17)中介者模式
本笔记摘抄自:https://www.cnblogs.com/PatrickLiu/p/7966240.html,记录一下学习过程以备后续查用. 一.引言 今天我们要讲行为型设计模式的第五个模式--中 ...
随机推荐
- JavaScript Json对象和Json对象字符串的关系 jsonObj<->JsonString
JavaScript Json对象和Json对象字符串的关系 jsonObj<->JsonString 如下示例: 直接写的a1就是一个Json对象,a2 就是一个Json对象字符串; 通 ...
- python守护线程
如果你设置一个线程为守护线程,就表示你在说这个线程是不重要的,在进程退出的时候,不用等待这个线程退出.如果你的主线程在退出的时候,不用等待那些子线程完成,那就设置这些线程的daemon属性.即在线程开 ...
- C#设计模式系列:代理模式(Proxy)
代理模式提供了一个中介控制对某个对象的访问.现实生活中,我们可能会用支票在市场交易中用来代替现金,支票就是账户中资金的代理. 1.代理模式简介 1.1>.定义 代理模式(Proxy)定义:代理模 ...
- sizzle分析记录:getAttribute和getAttributeNode
部分IE游览器下无法通过getAttribute取值? <form name="aaron"> <input type="text" name ...
- ListView+CheckBox实现全选 单击效果
在网上也找了一些案例,但都是用Map来实现的.我的是把对象绑定到当前控件上.代码稍微简洁. main布局文件:main.xml <?xml version="1.0" enc ...
- 【重磅开源】Hawk-数据抓取工具:简明教程
Hawk-数据抓取工具:简明教程 标签(空格分隔): Hawk Hawk: Advanced Crawler& ETL tool written in C#/WPF 1.软件介绍 HAWK是一 ...
- Rust初步(三):使用atom搭配racer进行rust编程
在rust.cc社区中有一个关于rust编辑器的讨论(话说很多人要学一个新语言,都会立即考虑编辑器的问题,包括我在内),主要关注的是,智能提示(这个真的太重要了).大家讨论下来有几个选择 1. ecl ...
- ASP.NET WebForms MapPageRoute 路由配置
MapPageRoute 应该是 ASP.NET 4.0 中的东西,但现在我是第一次使用它,使用场景是:MVC 混合使用 WebForm,然后对 WebForm 进行路由配置,当然也可以使用 ISAP ...
- C#运用GmaQrCode生成二维码
项目中需要生成二维码,方法比较多,可以采用JS插件,也可以采用第三方插件后台生成二维码,在后台方法中可以采用QRCode或者GmaQrCode,现在介绍一种C#在后台生成二维码的方法: /// < ...
- [emacs] 使用ggtags浏览代码
[emacs] 使用ggtags浏览代码 // */ // ]]> [emacs] 使用ggtags浏览代码 Table of Contents 1 相关的连接 2 global简介 2.1 ...