概要
动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
类图

运行

代码
using System;
namespace 装饰模式
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Client client = new Client();
client.main();
Console.ReadLine();
}
interface IComponent
{
void operation();
}
class SortComponent : IComponent
{
public void operation()
{
Console.WriteLine("发射炮弹");
}
}
class RunComponent : IComponent
{
public void operation()
{
Console.WriteLine("跑");
}
}
abstract class Decorator : IComponent
{
public Decorator(IComponent component)
{
this.component = component;
}
private IComponent component;
public void operation()
{
this.component.operation();
addedBehaivor();
}
public abstract void addedBehaivor();
}
class ArmDecorator : Decorator
{
public ArmDecorator(IComponent component) : base(component){}
public override void addedBehaivor()
{
Console.WriteLine("红外瞄准");
}
}
class GpsDecorator : Decorator
{
public GpsDecorator(IComponent component) : base(component) { }
public override void addedBehaivor()
{
Console.WriteLine("卫星定位");
}
}
class Client
{
public void main()
{
SortComponent sortComponent = new SortComponent();
ArmDecorator armDecorator = new ArmDecorator(sortComponent);
GpsDecorator gpsDecorator = new GpsDecorator(armDecorator);
gpsDecorator.operation();
}
}
}
}
英语
component
adj. 组成的,构成的; n. 成分; 组件; [电子] 元件
operation
n. 操作; 经营; [外科] 手术; [数][计] 运算
decorator
n. 装饰者; 室内装潢师
concrete
adj. 混凝土的; 实在的,具体的; 有形的; vi. 凝结; vt. 使凝固; 用混凝土修筑;
本文介绍了一种设计模式——装饰模式,该模式允许在不改变对象结构的前提下,动态地给对象添加新的职责。通过装饰模式,可以更加灵活地为对象增加功能,相比生成子类的方式更具优势。文章通过.NET的示例代码详细展示了装饰模式的实现。
3226

被折叠的 条评论
为什么被折叠?



