java 裝飾者類

來源:互聯網
上載者:User

標籤:代碼結構   system   優點   gen   string   體系   over   讀書   color   

裝飾者模式:增強一個類的功能還可以讓裝飾者類之間互相裝飾。


裝飾者模式和繼承的區別:

繼承實現的增強類:
  優點:代碼結構清晰,而且實現簡單
  缺點:對於每一個的需要增強類都要建立具體的子類來協助其增強,這樣會導致繼承體系過於龐大。


裝飾模式實現的增強類:
  優點:內部可以通過多態技術對多個需要增強類進行增強
  缺點:需要內部通過多態技術維護需要增強類的執行個體。進而使得代碼稍微複雜。

 

下面來個例子來實現裝飾者模式的效果

 1 //1.建立一個需要繼承的父類(或者需要擴充功能的類) 2 class Person { 3     public void study() { 4         System.out.println("學習"); 5     } 6 } 7  8 //2.裝飾者類(子類) 9 class Student1 extends Person{10     //2.1子類中維護一個父類(被裝飾者類)11     Person student;12     //2.2構造方法,裡面傳一個被裝飾者類的對象13     public Student1(Person student) {14         this.student = student;15     }16     17     //2.3複寫被裝飾者類的 需要擴充的方法18     @Override19     public void study() {20         student.study();21         //2.4對方法進行擴充,添加“讀書”這一方法22         System.out.println("讀書");    23     }24     25 }26 27 //3.類似前面的對被裝飾者方法進行擴充另一個方法28 class Student2 extends Person{29     Person student;30     public Student2(Person student) {31         this.student  = student ;32     }33 34     @Override35     public void study() {36         // TODO Auto-generated method stub37         student.study();38         //另一個擴充方法,“寫字”39         System.out.println("寫字");40     }41 }42 43 44 class Student3 extends Person{45     Person student;46     47     public Student3(Person student) {48         this.student  = student ;49     }50 51     @Override52     public void study() {53         // TODO Auto-generated method stub54         student.study();55         //另一個擴充方法,“畫畫”56         System.out.println("畫畫");57     }58 }59 60 61 public class readerExt {62 63     public static void main(String[] args) {64         65         //5.建立被裝飾者類的對象66         Person person = new Person();67         person.study();  //學習68         69         //5.1建立裝飾者類(子類)的對象,傳入被裝飾者類的對象70         Student1 s1 = new Student1(person);71         s1.study();  //學習,讀書72         73         Student2 s2 = new Student2(person);74         s2.study();  //學習,寫字75         76         //5.2 裝飾者 互相裝飾77         Student3 s3 = new Student3(s2);78         s3.study();  //學習,讀書,畫畫79         80     }    81 }

 

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.