装饰模式,利用了setComponent来对对象进行包装。
输出:
第一种装扮
T恤 垮裤 破球鞋 装扮的kingc
第二种装扮
西装 领带 皮鞋 装扮的kingc
class Person {
private String name;
public Person(){}
public Person(String name){
this.name = name;
}
public void show() {
System.out.println("装扮的" + name);
}
}
// 装饰类
class Decorator extends Person{
protected Person person;
public void setComponent(Person person){
this.person = person;
}
public void show(){
if(person != null)
person.show();
}
}
// 不同的装饰
class Tshirts extends Decorator{
public void show(){
System.out.print("T恤 ");
super.show();
}
}
class BigTrouser extends Decorator{
public void show(){
System.out.print("垮裤 ");
super.show();
}
}
class Sneakers extends Decorator{
public void show(){
System.out.print("破球鞋 ");
super.show();
}
}
class LeatherShoes extends Decorator{
public void show(){
System.out.print("皮鞋 ");
super.show();
}
}
class Suit extends Decorator{
public void show(){
System.out.print("西装 ");
super.show();
}
}
class Tie extends Decorator{
public void show(){
System.out.print("领带 ");
super.show();
}
}
public class Test{
public static void main(String[] args){
Person person = new Person("kingc");
System.out.println("第一种装扮");
Sneakers sk = new Sneakers();
BigTrouser bt = new BigTrouser();
Tshirts ts = new Tshirts();
sk.setComponent(person);
bt.setComponent(sk);
ts.setComponent(bt);
ts.show();
System.out.println("第二种装扮");
LeatherShoes ls = new LeatherShoes();
Tie tie = new Tie();
Suit suit = new Suit();
ls.setComponent(person);
tie.setComponent(ls);
suit.setComponent(tie);
suit.show();
}
}
输出:
第一种装扮
T恤 垮裤 破球鞋 装扮的kingc
第二种装扮
西装 领带 皮鞋 装扮的kingc