Person类:
public class Person {
public Person(){};
private String name;
public Person(String name){
this.name = name;
}
public void Show(){
System.out.print("装扮:"+ name);
};
}
服饰类:
public class Finery extends Person{
protected Person component;
//打扮
public void Decorate(Person component){
this.component = component;
}
public void Show(){
if(component != null){
component.Show();
}
}
}
具体服饰类:
public class TShirt extends Finery{
public void Show(){
System.out.print("T许");
super.Show();
}
}
public class Shoes extends Finery{
public void Show(){
System.out.print("鞋");
super.Show();
}
}
客户端代码:
public class test {
public static void main(String[] args){
Person xc = new Person("小秋");
TShirt tShirt = new TShirt();
Shoes shoes = new Shoes();
tShirt.Decorate(xc);
shoes.Decorate(tShirt);
shoes.Show();
}
}
运行结果:
总结:
1、本例中Decorate方法是重点
2、动态地扩展,不必改变原类文件和使用继承