HeadFirst design pattern筆記-裝飾者模式

來源:互聯網
上載者:User

裝飾者模式:動態地將責任附加到對象上,提供了比繼承更有彈性的替代方案

裝飾者模式的特點:

1.裝飾者和被裝飾者有相同的父類

2.可以用一個或者多個裝飾者封裝一個對象

3.可以在運行時動態地用裝飾者來裝飾對象

4.裝飾者可以在其被裝飾者的行為(方法)前/後,加上自己的行為

裝飾者與繼承的方法不同的是,如果依賴繼承,有新的行為時,要修改現有的方法,而裝飾者模式不用修改已有的類的方法,直接new一個裝飾者去封裝這個現有的類就可以了。當然這樣也會帶來缺點,常常會造成設計中有大量的小類,JAVA的I/O便是這種情況。

Java I/O中裝飾者的例子:

new DataInputStream(new BufferedInputStream(bew FileInputStream(xxx)));

DataInputStream和BufferedInputStream都擴充自FilterInputStream

編寫自己的IO裝飾者:

把輸入資料流內的大寫字母轉換成小寫

import java.io.FilterInputStream;import java.io.IOException;import java.io.InputStream;public class LowerCaseInputStream extends FilterInputStream{protected LowerCaseInputStream(InputStream in) {super(in);}@Overridepublic int read() throws IOException {int c = super.read();return (c == -1 ? c : Character.toLowerCase((char)(c)));}@Overridepublic int read(byte[] b, int off, int len) throws IOException {int result = super.read(b, off, len);for (int i = off; i < result + off; i++) {b[i] = (byte)Character.toLowerCase((char)b[i]);}return result;}}

測試:

import java.io.BufferedInputStream;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;public class Test {public static void main(String[] args) throws IOException {InputStream in = new LowerCaseInputStream(new BufferedInputStream(new ByteArrayInputStream("TEST THE STREAM".getBytes())));int c = 0;while ((c = in.read()) >= 0) {System.out.print((char)c);}in.close();}}

結果:

test the stream

聯繫我們

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