version1.0
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public void wearTshirt() {
System.out.println("大T恤");
}
public void wearTtrouser() {
System.out.println("垮裤");
}
public void wearSneakers() {
System.out.println("破球鞋");
}
public void wearSuit() {
System.out.println("西装");
}
public void wearTie() {
System.out.println("领带");
}
public void wearLeatherShoes() {
System.out.println("皮鞋");
}
public void show() {
System.out.println("装扮的" + name);
}
}
public class Customer {
public static void main(String[] args) {
Person xc = new Person("老大");
System.out.println("\n第一种装扮:");
xc.wearTshirt();
xc.wearTtrouser();
xc.wearSneakers();
xc.show();;
System.out.println("\n第二种装扮");
xc.wearSuit();
xc.wearTie();
xc.wearLeatherShoes();;
xc.show();
}
}
-------------------------------
version2.0
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
}
public abstract class Finery {
public abstract void show();
}
public class Tshirt extends Finery {
@Override
public void show() {
System.out.println("大T恤");
}
}
public class Ttrouser extends Finery {
@Override
public void show() {
System.out.println("垮裤");
}
}
public class Sneakers extends Finery {
@Override
public void show() {
System.out.println("破球鞋");
}
}
public class Suit extends Finery {
@Override
public void show() {
System.out.println("西装");
}
}
public class Tie extends Finery {
@Override
public void show() {
System.out.println("领带");
}
}
public class LeatherShoes extends Finery {
@Override
public void show() {
System.out.println("皮鞋");
}
}
public class Customer {
public static void main(String[] args) {
Person ld = new Person("老大");
System.out.println("第一种装扮:");
Finery dtk = new Tshirt();
Finery kk = new Ttrouser();
Finery pqx = new Sneakers();
dtk.show();;
kk.show();
pqx.show();
ld.show();
System.out.println("第二种装扮:");
Finery xz = new Suit();
Finery dld = new Tie();
Finery px = new LeatherShoes();
xz.show();
dld.show();
px.show();
ld.show();
}
}
装饰模式Decorator:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。