代码:
abstract class AbstractPerson{
public abstract void show();
protected String str;
}
class Person extends AbstractPerson{
Person(){
this.str="anything";
}
public void show(){
System.out.println(this.str);
}
}
abstract class AbstractDecorate extends AbstractPerson{
protected AbstractPerson person;
}
class Coat extends AbstractDecorate{
Coat(AbstractPerson person){
this.person=person;
}
public void show(){
this.str=this.person.str+"wear a coat";
System.out.println(this.str);
}
}
class Trousers extends AbstractDecorate{
Trousers(AbstractPerson person){
this.person=person;
}
public void show(){
this.str=this.person.str+"wear a trousers";
System.out.println(this.str);
}
}
class Demo{
public static void main(String[] argv){
Person pd = new Person();
pd.show();
Coat cd=new Coat(pd);
cd.show();
Trousers td=new Trousers(cd);
td.show();
}
}
思路:
我们先有一个抽象的基类
然后有一个人的具体实现类
写一个装饰者类,继承于基类,用来抽象出我们具体实现某种装饰行为的基类
然后就可以写我们的具体装饰行为类
把具体装饰类的构造函数用来构建出基于我们要装饰的类
具体装饰类在写我们的行为来装饰自身