十一、裝飾器模式

裝飾器 Decorator 

容許向一個現有的對象添加新的功能,同時又不改變其結構。這種設計類型屬於結構性模式,它是做爲現有類的一個包裝設計模式

這種設計模式建立了一個裝飾類,用來包裝原有的類,並在保持類方法簽名完整的前提下,提供額外的功能。this

意圖:動態滴給一個對象添加一些額外的職責,就增長功能來講,裝飾器相比於生成子類,更加靈活

何使使用裝飾器: 在不想增長子類的狀況下,擴展類spa

優勢:裝飾類和被裝飾類能夠獨立發展,不會相互耦合,裝飾模式是繼承的一個替代模式,裝飾模式能夠動態擴展一個實現類的功能。設計

缺點:多層裝飾比較複雜。code

使用場景: 一、擴展一個類的功能。 二、動態增長功能,動態撤銷。component

 

 

//基礎接口
public interface Component {
    
    public void biu();
}
//具體實現類
public class ConcretComponent implements Component {

    public void biu() {
        
        System.out.println("biubiubiu");
    }
}
//裝飾類
public class Decorator implements Component {

    public Component component;
    
    public Decorator(Component component) {
        
        this.component = component;
    }
    
    public void biu() {
        
        this.component.biu();
    }
}
//具體裝飾類
public class ConcreteDecorator extends Decorator {

    public ConcreteDecorator(Component component) {

        super(component);
    }

    public void biu() {
        
        System.out.println("ready?go!");
        this.component.biu();
    }
}
//使用裝飾器
  Component component = new ConcreteDecorator(new ConcretComponent());
  component.biu();

  //console:
  ready?go!
  biubiubiu
相關文章
相關標籤/搜索