首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

装点者模式

2012-07-02 
装饰者模式装饰者模式动态地将责任附加到对象上? 若要扩展功能,提供了比继承更有弹性的替代方案,那就是

装饰者模式

装饰者模式>>>动态地将责任附加到对象上? 若要扩展功能,提供了比继承更有弹性的替代方案,那就是组合。

?

这也满足了高效java推荐的方法:尽量用组合来替代继承?

?

装饰者和被装饰者(即被包装的组件)必须是一样的类型,也就是说有共同的超类,为什么呢,因为装饰者必须能取代被装饰者

?

Java/Io系统就是一个典型的装饰器模式

?? 装饰组件是InputStream? 装饰器FilterInputStream? 如果要扩展 只需要继承FilterInputStream 重写read()方法就行了

?

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

public class LowerCaseInputStream extends FilterInputStream{

??? protected LowerCaseInputStream(InputStream in) {
??????? super(in);
??? }
???
??? //争对字节
??? public int read() throws IOException{
??????? int c = super.read();
??????? return (c == -1 ? c : Character.toLowerCase((char)c));
??? }
???
??? //争对字节数组
??? public int read(byte[] b,int offset,int length) throws IOException{
??????? int result = super.read(b, offset, length);
??????? for(int i = offset ; i < offset + result ;? i ++) {
??????????? b[i] = (byte)Character.toLowerCase((char)b[i]);
??????? }
??????? return result;
??? }
???
??? public static void main(String[] args) {
??????? int c ;
??????? try {
??????????? //一层层的装饰
??????????? InputStream in = new LowerCaseInputStream(
??????????????????? new BufferedInputStream(new FileInputStream("D://test.txt")));
??????????? while((c = in.read()) >= 0 ) {
??????????????? System.out.println((char)c);
??????????? }
??????? } catch (IOException e) {
??????????? e.printStackTrace();
??????? }
??? }
}

热点排行