java设计模式-装饰者模式

99 阅读1分钟

1.简介

装饰器模式是基于对象组合的方式来动态给对象添加所需要的功能。

装饰器会持有一个构件对象的实例。

2.场景

有时候我们想增强类的方法,使用装饰器可以代替继承,使用更加灵活。

3.类图

装饰器类图.jpg

4.demo

 
//对应图片中的Componet
public interface Coat{
  public void show();
}
//对应图片中的ConcreteComponent
public class CoatImpl implements Coat {
  public void show(){
    sout("原始show方法")
  }
}
//对应图片中的ConcreteDecorator
public class TDress implements Coat{
  //持有实现接口对象的引用
  public Coat coat;
  
  public TDress(Coat coat){
    super();
    this.coat = coat;
  }
  
  public void show(){
    coat.show();
    sout("装饰器TDress")
  }
}
//对应图片中的ConcreteDecorator
public class TShirt implements Coat {
  public Coat coat;
  
  public Tshirt(Coat coat){
    super();
    this.coat = coat;
  }
  
  public void show(){
    coat.show();
    sout("装饰器TShirt");
  }
}
//测试类
public class Test{
  psvm{
    Coat coat = new CoatImpl();
    Coat tshirt = new Tshirt(coat);
    tshirt.show();
    Caot tdress = new TDress(coat);
    tdress.show();
  }
}

4.具体应用

java中:

InputStream代表Component对象
FileInputStream代表ConcreteComponent对象
FilterInputStream代表Decorator对象,并持有InputStream对象实例的引用
BufferedInputStream、DataInputStream等代表ConcreteDecorator对象