装饰模式:动态的给一个对象添加一些额外的职责
应用场景:
动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。不改变接口的前提下,增强所考虑的类的性能。
何时使用:
1)需要扩展一个类的功能,或给一个类增加附加责任。
2)需要动态的给一个对象增加功能,这些功能可以再动态地撤销。
3)需要增加一些基本功能的排列组合而产生的非常大量的功能,从而使继承变得 不现实。
例子来自大话设计模式
可倒推理解代码
//装饰模式
class Person
{
public Person(){}
private String name;
public Person(String name){
this.name = name;
}
public void show(){
System.out.println("装扮的"+name);
}
}
//服饰类
class Finery extends Person
{
protected Person component;
public void Decorate(Person component){
this.component = component;
}
public void show(){
if(component != null){
component.show();
}
}
}
class TShirts extends Finery
{
public void show(){
System.out.println("大T恤");
super.show();
}
}
class BigTrouser extends Finery
{
public void show(){
System.out.println("垮裤");
super.show();
}
}
class Sneakers extends Finery
{
public void show(){
System.out.println("球鞋");
super.show();
}
}
public class Main {
public static void main(String[] args) {
Person xc = new Person("小菜");
System.out.println("第一种装扮:");
Sneakers s = new Sneakers();
BigTrouser bt = new BigTrouser();
TShirts ts = new TShirts();
s.Decorate(xc);
bt.Decorate(s);
ts.Decorate(bt);
ts.show();
System.out.println("第二种装扮:");
bt.Decorate(xc);
s.Decorate(bt);
ts.Decorate(s);
ts.show();
}
}