图1:
图2:
Component是定义一个对象接口,可以给这些对象动态地添加职责。ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需要知道Decorator的存在的。至于ConcreteDecorator就是具体的装饰对象,起到给Component添加职责的功能。
View Code
public class Text{ //测试端代码 public static void main(String[] args){ Person person = new Person("傻馒"); System.out.println("第一种装扮:"); Tshirts t = new Tshirts(); BigTrouser b = new BigTrouser(); t.decorate(person); b.decorate(t); b.show(); } } //人类(*** ConcreteComponent ***) class Person{ private String name; public Person(){} public Person(String name){ this.name = name; } public void show(){ System.out.println("装扮的"+name); } } //服饰类(*** Decorator ***) class Finery extends Person{ protected Person component; public void decorate(Person component){ this.component = component; } public void show(){ if(null != component){ component.show(); } } } //具体服饰类(*** ConcreteDecorator ***) class Tshirts extends Finery{ public void show(){ super.show(); System.out.println("大T恤"); } } class BigTrouser extends Finery{ public void show(){ super.show(); System.out.println("大裤衩"); } }