- 属于结构型设计模式
- 优点:动态给对象添加功能,比生成子类更加灵活
- 缺点:增加类的数量
- 装饰器模式应用在 IO 中的 Buffered�
- 装饰器模式应用在 filter 中
今天通过装饰器模式来实现一个披着羊皮的狼
public interface Animal {
void shout();
void appearance();
}
public class Wolf implements Animal {
@Override
public void shout() {
System.out.println("I am a Wolf");
}
@Override
public void appearance() {
System.out.println("I have gray fur");
}
}
public class SheepWolf implements Animal {
Animal animal;
public SheepWolf(Animal animal) {
this.animal = animal;
}
@Override
public void shout() {
animal.shout();
}
@Override
public void appearance() {
animal.appearance();
System.out.println("I also have sheepskin");
}
}
// 测试类
public class Main {
public static void main(String[] args) {
Animal animal = new SheepWolf(new Wolf());
animal.shout();
animal.appearance();
}
}
// 结果
I am a Wolf
I have gray fur
I also have sheepskin