Skip to content

Latest commit

 

History

History
78 lines (67 loc) · 1.52 KB

Decorator.md

File metadata and controls

78 lines (67 loc) · 1.52 KB

介绍

  • 属于结构型设计模式
  • 优点:动态给对象添加功能,比生成子类更加灵活
  • 缺点:增加类的数量
  • 装饰器模式应用在 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