装饰模式(Dcorator),动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
主函数
public class main {
public static void main(String[] args) {
Person xc = new Person("小菜");
System.out.println("\n第一种装扮");
Sneakers pqx = new Sneakers();
BigTrouser kk = new BigTrouser();
TShirts dtx = new TShirts();
pqx.Decorate(xc);
kk.Decorate(pqx);
dtx.Decorate(kk);
dtx.Show();
System.out.println("\n第二种装扮");
LeatherShoes px = new LeatherShoes();
Tie ld = new Tie();
Suit xz = new Suit();
px.Decorate(xc);
ld.Decorate(px);
xz.Decorate(ld);
xz.Show();
}
}
装饰器父类(顶级类)
public class Person {
public Person() {
}
private String name;
public Person(String name) {
this.name = name;
}
public void Show() {
System.out.println("装扮的{"+name+"}");
}
}
子类
public class Finery extends Person {
protected Person component;
public void Decorate(Person component) {
this.component = component;
}
@Override
public void Show() {
if(component != null)
this.component.Show();
}
}
孙子类
public class Sneakers extends Finery {
public void Show() {
System.out.print("破球鞋 ");
super.Show();
}
}
public class BigTrouser extends Finery {
public void Show() {
System.out.print("垮裤 ");
super.Show();
}
}
public class Suit extends Finery {
public void Show() {
System.out.print("西装 ");
super.Show();
}
}
public class Tie extends Finery {
public void Show() {
System.out.print("领带 ");
super.Show();
}
}
public class TShirts extends Finery {
public void Show() {
System.out.print("大T恤 ");
super.Show();
}
}
public class LeatherShoes extends Finery {
public void Show() {
System.out.print("皮鞋 ");
super.Show();
}
}