Java軟體設計模式------裝飾設計模式

來源:互聯網
上載者:User

標籤:mini   裝飾模式   tor   定義   ram   學習   nbsp   his   rman   

Java軟體設計模式一共分為23種;

一般常用的有:

  單例設計模式

  裝飾設計模式

  工廠設計模式

 

裝飾設計模式

定義:英文叫Decorator Pattern,又叫裝飾者模式。裝飾模式是在不必改變原類檔案和使用繼承的情況下,動態地擴充一個對象的功能。它是通過建立一個封裝對象,也就是裝飾來包裹真實的對象。

在生活中我們用程式員和專案經理的例子來比喻,專案經理是從程式員開始的,經過不斷地積累工作經驗、不斷的學習新的知識,才有可能升職。

在裝飾設計模式中專案經理就是程式員的增強。

程式猿:
  寫程式
專案經理
  調研需求
  寫程式
  專案管理

1.建立一個程式員類

/**
* 程式員
* @author Administrator
*/
public class Programmaer {
public void code(){
System.out.println("寫代碼..");
}
}

2.建立一個專案經理類(專案經理是在程式員基礎上增加新的工作方法)

/**
* 專案經理
* @author Administrator
*/
public class ProgramerMannerger {
private Programmaer p;
//構造方法 參數為程式員的引用
public ProgramerMannerger(Programmaer pr){
this.p=pr;
}
//專案經理工作的方法
public void work(){
System.out.println("調研需求");
p.code(); //程式員的方法
System.out.println("專案管理");

}
}

3.建立一個Test類:

/**
* 在程式員基礎上加功能,用封裝設計模式加功能
* @author Administrator
*/
public class Test2 {
public static void main(String[] args) {
//程式員
Programmaer p=new Programmaer();
//專案經理
ProgramerMannerger pm=new ProgramerMannerger(p);
pm.work();
}
}

結論:當一個程式完成以後,怎樣增加功能,又不用大範圍的修改代碼?就可以使用裝飾設計模式。

Java軟體設計模式------裝飾設計模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.