decorator的结构如下:
MyInterface
|
_______|_______
| |
Myclass Decorator
____|_____
| |
DecoratorA DecoratorB
decorator的目的是在不改变基础类的前提下,添加新的功能(在比较少的子类前提),Myclass是你的扩展类,decoratorA,decoratorB封装了你要扩展的功能,并保持了 MyInterface的引用
考虑一下代码
public static void main(String[]args){
MyInterface a=new Myclass();
a.print();
}
MyInterface是Myclass的接口,在 MyInterface里面就声明了一个print方法,myclass实现了该方法
public void print(){
System.out.print("hello");
}
如果我们要实现打印 ”hello word“,”my hell“就要要写很多类似的类,
decorator装饰模式的解决方法就是,只实现基本功能,附加功能都抽出来,
public decoratorA implements Decorator{
MyInterface myObject;
public decoratorA(MyInterface my){
myObject=my;
}
public void print(){
System.out.print(" world ");
}
}
public decoratorB implements Decorator{
MyInterface myObject;
public decoratorB(MyInterface my){
myObject=my;
}
public void print(){
System.out.print("MY ");
myObject.print();
}
}
这时需要实现my hello word就比较简单了
public void main(String[]args){
MyInterface a=new decoratorA (new decoratorB(new Myclass()) );
a.print();
}
BufferedInputStream bis = new BufferedInputStream(new DataInpuStream(new FileInputStream("xxx.txt")));
InputStream.为例:
java.io.InputStream
|
_______________________|________________________
| |
ByteArrayInputStream FilterInputStream
StringBufferInputStream _____________________|____________________________
FileInputStream | | | |
PipedInputStream DataInputStream BufferedInputStream LineNumInpuStream PushbackInputStream
基础的流只有左边4个,这些流代表了数据的来源,所有的流都必须从这四个中之一开始(注,还有一个RandomAccessFile、File,这两个不在本文介绍范围)。
当我们需要什么新功能的时候就在右边找个装饰类,在用到缓存的时候我们就用bufferedInputStream
BufferdInputStream is = new BufferedInputStream(new FileInputStream("xxx.txt"));
假如再要DataInputStream的功能,只要在加一层:
DataInputStream dis = new DataInputStream(new BufferdInputStream(new FileInputStream));
分享到:
相关推荐
C#设计模式之Decorator 装饰模式,pdf+视频教学,实例演示,易学易用~~
学习java 装饰模式(decorator)非常好的例子
C#面向对象设计模式 Decorator 装饰模式 视频讲座下载
C#面向对象设计模式纵横谈(10):Decorator 装饰模式(结构型模式) (Level 300)
C#面向对象设计模式纵横谈(10):Decorator 装饰模式(结构型模式)
在这里与各位分享本人从网络上下载的C#面向对象设计模式纵横谈系列视频,共有25节,除了第一节需要各位贡献一点资源分以作为对本人上传资源的回馈,后面的其他资源均不需要... 这是第10节:结构型模式Decorator装饰模式
装饰器(Decorator)模式 详细教程,简明易懂,非常清晰的,附带有代码示例。
设计模式C++学习之装饰模式(Decorator)
奇幻RPG(物品锻造 与 Decorator模式)本文中,我们通过一个常见的给武器(对象)添加宝石(额外的状态和行为)的例子,讨论了Decorator设计模式的实现过程。
动态地给一个对象添加一些额外的职责。就扩展功能而言,它比生成子类方式更为灵活。
NULL 博文链接:https://janeky.iteye.com/blog/472502
Head First学习笔记+Head First之装饰者模式高清PDF
Java-从Decorator,Adapter模式看Java/IO 讲得很详细
装饰模式.doc 装饰模式.doc 装饰模式.doc
博文链接:https://your.iteye.com/blog/133420
5、装饰模式(Decorator) 用意:动态地给一个对象增加其它职责,比继承实现灵活。
NULL 博文链接:https://dalongjdk.iteye.com/blog/815545
java Decorator设计模式应用,可以简单了解它,初学者入。
装饰者模式(Decorator Pattern)是一种结构型设计模式,它的定义是在不改变原有对象结构的基础上,动态地给该对象增加一些职责(即增加其额外功能)。这种模式允许向一个现有的对象添加新的功能,同时又不改变其...
“就增加功能来说,Decorator 模式相比生成子类更为灵活” 这句话的含义是,组合比继承更灵活,当可拓展的功能很多时,继承方案会产生大量的子类,而组合可以提