装饰模式
装饰模式
public class Person {
private String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
public void show() {
System.out.println("装扮的"+name);
}
}
public class Finery extends Person{
protected Person person;
@Override
public void show() {
if (this.person!=null) {
person.show();
}
}
public void decorator(Person person) {
this.person = person;
}
}
针对于各个服饰继承服饰类实现各个服饰public class LeatherShoes extends Finery{
@Override
public void show() {
System.out.println("皮鞋、");
super.show();
}
}
public class Necktie extends Finery{
@Override
public void show() {
System.out.println("领带、");
super.show();
}
}
等等。。。public static void main(String[] args) {
Person xiaoming = new Person("小明");
Finery tshirt = new TShirts();
Finery jeans = new Jeans();
Finery leatherShoes = new LeatherShoes();
jeans.decorator(xiaoming);
tshirt.decorator(jeans);
leatherShoes.decorator(tshirt);
leatherShoes.show();
Finery sneaker = new Sneaker();
Finery shorts = new Shorts();
shorts.decorator(xiaoming);
tshirt.decorator(shorts);
sneaker.decorator(tshirt);
sneaker.show();
}
输出结果
皮鞋、
T恤、
牛仔裤、
装扮的小明
运动鞋、
T恤、
短裤、
装扮的小明