示例名称:超级递送员
示例说明:定义基类(BaseDelivery)和虚方法(Deliver),定义继承自该基类的三个子类(MilkDelivery、NewspaperDelivery和CarDelivery),重写基类的虚方法(Deliver)。
示例类图:
设计模式示例二 Decorator(装饰者)
关键部分说明

BaseDelivery
设计模式示例二 Decorator(装饰者)using System;
设计模式示例二 Decorator(装饰者)
设计模式示例二 Decorator(装饰者)
namespace
 Delivery
Deliver是虚方法,子类需要重写它。

MilkDelivery、NewspaperDelivery和CarDelivery
设计模式示例二 Decorator(装饰者)using System;
设计模式示例二 Decorator(装饰者)
设计模式示例二 Decorator(装饰者)
namespace
 Delivery

这三个类分别继承了BaseDelivery(is a的关系),含有一个BaseDelivery类型的私有字段和一个BaseDelivery参数的构造方法,重写父类BaseDelivery的Deliver方法。

应用
设计模式示例二 Decorator(装饰者)using System;
设计模式示例二 Decorator(装饰者)
using System.Collections.Generic;
设计模式示例二 Decorator(装饰者)
using System.Text;
设计模式示例二 Decorator(装饰者)
设计模式示例二 Decorator(装饰者)
namespace Delivery
任何继承了BaseDelivery的子类都可以做为其它子类的构造函数的参数传递。即可实现对该子类的装饰(Decorator)。

运行结果
设计模式示例二 Decorator(装饰者)

现在是不是很开心!

相关文章: