实例代码:
// 抽象类 Girl
public abstract class Girl {
String description = "no particular";
public String getDescription(){
return description;
}
}
// 美国女孩
public class AmericanGirl extends Girl {
public AmericanGirl() {
description = "+AmericanGirl";
}
}
// 国产妹子
public class ChineseGirl extends Girl {
public ChineseGirl() {
description = "+ChineseGirl";
}
}
// 装饰者
public abstract class GirlDecorator extends Girl {
public abstract String getDescription();
}
// 下面以美国女孩示例
// 给美国女孩加上金发
public class GoldenHair extends GirlDecorator {
private Girl girl;
public GoldenHair(Girl g) {
girl = g;
}
@Override
public String getDescription() {
return girl.getDescription() + "+with golden hair";
}
}
// 加上身材高大的特性
public class Tall extends GirlDecorator {
private Girl girl;
public Tall(Girl g) {
girl = g;
}
@Override
public String getDescription() {
return girl.getDescription() + "+is very tall";
}
}
// 检验一下
public class Main {
public static void main(String[] args) {
Girl g1 = new AmericanGirl();
System.out.println(g1.getDescription());
GoldenHair g2 = new GoldenHair(g1);
System.out.println(g2.getDescription());
Tall g3 = new Tall(g2);
System.out.println(g3.getDescription());
// 你也可以一步到位
// Girl g = new Tall(new GoldenHair(new AmericanGirl()));
}
}
可以理解为:
当一个对象更新信息时,它会通知它的观测者们,并将自己的信息传递给它们,使它们更新自己的信息。