裝飾模式(Dcorator)谅海,動(dòng)態(tài)地給一個(gè)對(duì)象添加一些額外的職責(zé),就增加功能來(lái)說(shuō)蹦浦,裝飾模式比生成子類(lèi)更為靈活扭吁。
主函數(shù)
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();
}
}
裝飾器父類(lèi)(頂級(jí)類(lèi))
public class Person {
public Person() {
}
private String name;
public Person(String name) {
this.name = name;
}
public void Show() {
System.out.println("裝扮的{"+name+"}");
}
}
子類(lèi)
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();
}
}
孫子類(lèi)
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("領(lǐng)帶 ");
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();
}
}