package com.装饰模式;
public class Person {
private String name;
public Person(){}
public Person(String name)
{
this.name=name;
}
public void show(){
System.out.println("person:"+name);
}
}
package com.装饰模式;
public class Finery extends Person {
protected Person component;
public void Decorate(Person compotent){
this.component=compotent;//每个类都来继承Person
}
public void show(){
if(component!=null)
component.show();
}
}
package com.装饰模式;
public class TShirts extends Finery {
public void show() {
System.out.println("t恤");
super.show();//覆盖Finery的show方法,还要调用基类的
}
}
package com.装饰模式;
public class BigTrouser extends Finery {
public void show() {
System.out.println("垮裤");
super.show();//只是在构造方法的时候需要放在第一行
}
}
<pre name="code" class="java">package com.装饰模式;
public class Main {
public static void main(String[] args) {
Person xiaoguizi=new Person("小桂子");
TShirts t=new TShirts();
BigTrouser b=new BigTrouser();
t.Decorate(xiaoguizi);
b.Decorate(t);
b.show();
}
}
垮裤
t恤
person:小桂子