具体细节看书吧!
装饰模式:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
装饰模式是为已有功能动态添加更多功能的一种方式。
优点:把类中的装饰功能从类中搬移去除,这样可以简化原有的类,有效地把类的核心职责和装饰功能区分开了,而且可以去除相关类中重复的装饰逻辑。
使用时,装饰的顺序很重要,比如加密数据和过滤词汇都可以是数据持久化前的装饰功能,但若先加密了数据再用过滤功能就会出问题。最理想的情况,保证装饰类之间彼此独立。
//Component基类
public class Person
{
protected Person() { }
private string name;
protected Person(string name)
{
this.name = name;
}
public virtual void Show()
{
Debug.Log($"装扮的{name}");
}
}
//具体的某一派生类
public class XiaoMing : Person
{
public XiaoMing()
{
}
private string name;
public XiaoMing(string name)
{
this.name = name;
}
}
//装饰基类
public class Finery : Person
{
protected Person component;
public void Decorate(Person component)
{
this.component = component;
}
public override void Show()
{
if (component != null)
{
component.Show();
}
}
}
//具体装饰派生类
public class TShirts : Finery
{
public override void Show()
{
Debug.Log("大T恤");
base.Show();
}
}
//具体装饰派生类
public class BigTrouser : Finery
{
public override void Show()
{
Debug.Log("垮裤!");
base.Show();
}
}
使用:
Person person = new XiaoMing("小明");
TShirts shirts = new TShirts();
BigTrouser bigTrouser = new BigTrouser();
shirts.Decorate(person);
bigTrouser.Decorate(shirts);
bigTrouser.Show();
装饰也可在构造函数传入,只需添加相应的构造函数。
类似下面:
//具体装饰派生类
public class TShirts : Finery
{
public TShirts(Person component) : base(component)
{
}
public override void Show()
{
Debug.Log("大T恤");
base.Show();
}
}
//具体装饰派生类
public class BigTrouser : Finery
{
public BigTrouser(Person component) : base(component)
{
}
public override void Show()
{
Debug.Log("垮裤!");
base.Show();
}
}
Person person = new XiaoMing("小明");
TShirts shirts = new TShirts(person);
BigTrouser bigTrouser = new BigTrouser(shirts);
//或者这样:从右往左装饰
//BigTrouser bigTrouser = new BigTrouser(new TShirts(person));
bigTrouser.Show();