装饰模式(Decorator):动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
装饰模式结构图:
装饰模式实现代码:
/// <summary> /// 声明一个Component的抽象基类 /// </summary> abstract class Component { public abstract void Operation(); } /// <summary> ///声明一个具体的Component,继承Component /// </summary> class ConcreteComponent : Component { public override void Operation() { Console.WriteLine("ConcreteComponent.Operation()"); } } /// <summary> /// 声明一个抽象的装饰类‘Decorator‘ /// 并继承Component /// </summary> abstract class Decorator : Component { protected Component component; //装饰方法 public void SetComponent(Component component) { this.component = component; } //重写 Operation 方法 public override void Operation() { if (component != null) { component.Operation(); } } } /// <summary> /// 声明一个具体装饰类A,继承Decorator /// </summary> class ConcreteDecoratorA : Decorator { public override void Operation() { //一些功能扩展 Console.WriteLine("ConcreteDecoratorA.Operation()"); base.Operation(); } } /// <summary> /// 声明一个具体装饰类B,继承Decorator /// </summary> class ConcreteDecoratorB : Decorator { public override void Operation() { //一些功能扩展 AddedBehavior(); Console.WriteLine("ConcreteDecoratorB.Operation()"); base.Operation(); } //装饰类B自有方法 void AddedBehavior() { } } class Program { static void Main(string[] args) { ConcreteComponent c = new ConcreteComponent(); ConcreteDecoratorA d1 = new ConcreteDecoratorA(); ConcreteDecoratorB d2 = new ConcreteDecoratorB(); d1.SetComponent(c); d2.SetComponent(d1); d2.Operation(); Console.ReadKey(); } }
执行结果:
我们可以通过一个简单是实例,还应用一下装饰模式,比如现在有一种坦克,坦克有很多的型号和特色,有的具有红外功能,有的具有GPS定位功能,通过使用装饰模式,大大降低了子类的膨胀。
//坦克基类 public class Tank { /// <summary> /// 射击 /// </summary> public virtual void Shoot() { } } //T50 型坦克 public class T50Tank:Tank { public override void Shoot() { Console.WriteLine("T50 型号坦克射击"); } } //T51型坦克 public class T51Tank : Tank { public override void Shoot() { Console.WriteLine("T51 型号坦克射击"); } } //装饰基类 public abstract class Decorator : Tank { protected Tank tank; //利用构造器进行装饰 public Decorator(Tank tank) { this.tank = tank; } public override void Shoot() { if (tank != null) { tank.Shoot(); } } } //具有红外功能 public class InfraRed : Decorator { public InfraRed(Tank tank) : base(tank) { } public override void Shoot() { Console.WriteLine("带红外功能"); base.Shoot(); } } //具有GPS功能 public class GPS : Decorator { public GPS(Tank tank) : base(tank) { } public override void Shoot() { Console.WriteLine("带GPS功能"); base.Shoot(); } } class Program { static void Main(string[] args) { //声明一个T50型坦克 Tank t50Tank = new T50Tank(); //给T50型坦克赋予红外功能 InfraRed red = new InfraRed(t50Tank); //给T50型坦克赋予GPS功能 GPS gps = new GPS(red); gps.Shoot(); Console.ReadKey(); } }
执行结果:
原文:http://www.cnblogs.com/lxblog/p/4102485.html