Key words: Packaging
To an object moving state expand existing capacity to continuously package, continues to expand
Intent :
Add some additional responsibilities to an object dynamically. In terms of increasing functions, the D ecorator mode is more flexible than generating subclasses.
Applicable sex:
• Without affecting other objects, add responsibilities to individual objects in a dynamic and transparent manner.
• Deal with responsibilities that can be withdrawn.
• When the method of generating subclasses cannot be used for expansion. One situation is that there may be a large number of independent extensions, in order to support each combination will produce a large number of sub-categories, making the number of sub-categories explosive growth. Another situation may be because the class definition is hidden, or the class definition cannot be used to generate subclasses.
Case: (Various gems inlaid on weapons have different attributes)
namespace Decorator_DesignPattern
{
using System;
abstract class 武器
{
public abstract void 伤害();
}
class 宝剑 : 武器
{
public override void 伤害()
{
Console.WriteLine("宝剑基本行为 -伤害");
}
}
abstract class 装饰器 : 武器
{
public 武器 武器对象{get;set;}
public 装饰器(武器 c)
{
武器对象 = c;
}
public override void 伤害()
{
if (武器对象 != null)
武器对象.伤害();
}
public 武器 拆装饰()//!!!!
{
return 武器对象;
}
}
class 红宝石 : 装饰器
{
public 红宝石(武器 武器对象) : base(武器对象)
{
}
public override void 伤害()
{
base.伤害();
眩晕();
}
private void 眩晕()
{
Console.WriteLine(" 红宝石附加功能:眩晕....");
}
}
class 蓝宝石 : 装饰器
{
public 蓝宝石(武器 武器对象)
: base(武器对象)
{
}
public override void 伤害()
{
base.伤害();
冰冻();
}
private void 冰冻()
{
Console.WriteLine("蓝宝石附加功能:冰冻....");
}
}
/// <summary>
/// Summary description for Client.
/// </summary>
public class Client
{
public static void Main(string[] args)
{
武器 wq = new 宝剑();
//wq.伤害();
武器 wq2 = new 红宝石(new 蓝宝石(wq));
如何拆装备
//装饰器 zsq = (装饰器)wq2;
//武器 wq22= zsq.拆装饰();
wq2 = (wq2 as 装饰器).拆装饰();
wq2 = (wq2 as 装饰器).拆装饰();
wq2.伤害();
Console.ReadKey();
}
}
}