Java之裝飾模式(Decorator Pattern)

來源:互聯網
上載者:User

1. 概念

動態將職責附加到對象上,若要擴充功能,裝飾者提供了比繼承更具彈性的代替方案。它是通過建立一個封裝對象,也就是裝飾來包裹真實的對象。[由於繼承的靜態特質使其缺乏靈活性;且隨著子類的增多、組合,會導致更多子類的膨脹。類應設計的對擴充開放,對修改關閉。裝飾的意思:就是封裝一下。把另的對象封裝一下。]

2. UML圖

3.代碼

/************業務介面 Component************/
  public interface Component
{
void operation();
}

 

/************業務介面 Component************/
public class ConcreteComponent implements Component {
public void operation() {
//
}
}

 

/************裝飾 Decorator************/
public class Decorator implements Component
{
private Component component;

public Decorator(Component component)
{
this.component = component;
}

public void operation()
{
component.operation();
}
}

 


/************具體Decorator************/
    public class ConcreteDecorator extends Decorator
{
public ConcreteDecorator(Component component) {
super(component);
}

public void operation()
{
super.operation();

addBehavior();
}

private void addBehavior()
{
System.out.println("addBehavior");
}
}

 

/************運行樣本************/
        ConcreteDecorator concreteDecorator=new ConcreteDecorator(new ConcreteComponent());
        concreteDecorator.operation();

4.應用情境

1)需要擴充一個類的功能,或給一個類增加附加責任。

2)需要動態地給一個對象增加功能,這些功能可以再動態地撤銷。

3)需要增加由一些準系統的排列組合而產生的非常大量的功能,從而使繼承關係變得不現實。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.