装饰模式(Decorator):动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
package decorator;
/**
* 装饰模式(Decorator)
* Person类
*/
public class Person {
private String name;
public Person() {}
public Person(String name) {
this.name = name;
}
public void show() {
System.out.println("装扮的" + name);
}
}
package decorator;
/**
* 装饰模式(Decorator)
* 服饰类
*/
public class Finery extends Person {
protected Person component;
// 打扮
public void decorate(Person component) {
this.component = component;
}
@Override
public void show() {
if (component != null) {
component.show();
}
}
}
class TShirts extends Finery {
public void show() {
System.out.print("大T恤 ");
super.show();
}
}
class BigTrouser extends Finery {
public void show() {
System.out.print("大裤头 ");
super.show();
}
}
class Sneakers extends Finery {
public void show() {
System.out.print("破球鞋 ");
super.show();
}
}
class Suit extends Finery {
public void show() {
System.out.print("西装 ");
super.show();
}
}
class Tie extends Finery {
public void show() {
System.out.print("领带 ");
super.show();
}
}
class LeatherShoes extends Finery {
public void show() {
System.out.print("皮鞋 ");
super.show();
}
}
package decorator;
/**
* 装饰模式(Decorator)
* 客户端main方法
*/
public class Attire {
public static void main(String[] args) {
Person p0 = new Person("Kobe");
System.out.println("第一种装扮:");
TShirts tShirts = new TShirts();
BigTrouser bigTrouser = new BigTrouser();
Sneakers sneakers = new Sneakers();
tShirts.decorate(p0);
bigTrouser.decorate(tShirts);
sneakers.decorate(bigTrouser);
sneakers.show();
Person p1 = new Person("Allen");
System.out.println("第二种装扮:");
Suit suit = new Suit();
Tie tie = new Tie();
LeatherShoes leatherShoes = new LeatherShoes();
leatherShoes.decorate(p1);
tie.decorate(leatherShoes);
suit.decorate(tie);
suit.show();
}
}