设计模式-装饰者模式
何时用?
当某个对象的方法不适应业务需求时,通常有2种方式可以对方法进行增强:
编写子类,覆盖需增强的方法
使用Decorator设计模式对方法进行增强
疑问:在实际应用中遇到需增强对象的方法时,到底选用哪种方式呢?
没有具体的定式,不过有一种情况下,必须使用Decorator设计模式:即被增强的对象,开发人员只能得到它的对象,无法得到它的class文件。
比如request、response对象,开发人员之所以在servlet中能通过sun公司定义的HttpServletRequest\response接口去操作这些对象,是因为Tomcat服务器厂商编写了request、response接口的实现类。web服务器在调用servlet时,会用这些接口的实现类创建出对象,然后传递给servlet程序。
此种情况下,由于开发人员根本不知道服务器厂商编写的request、response接口的实现类是哪个?在程序中只能拿到服务器厂商提供的对象,因此就只能采用Decorator设计模式对这些对象进行增强。
怎么用?
Decorator设计模式的实现
1.首先看需要被增强对象继承了什么接口或父类,编写一个类也去继承这些接口或父类。
2.在类中定义一个变量,变量类型即需增强对象的类型。
3.在类中定义一个构造函数,接收需增强的对象。
4.覆盖需增强的方法,编写增强的代码。
举例:使用Decorator设计模式为BufferedReader类的readLine方法添加行号的功能。
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.nio.CharBuffer;
public class DecoratorDemo implements Closeable,Readable{
public BufferedReader bReader;
private int count = 0;
public DecoratorDemo(BufferedReader br) {
bReader = br;
}
@Override
public int read(CharBuffer cb) throws IOException {
int i = bReader.read();
return i;
}
@Override
public void close() throws IOException {
bReader.close();
}
public String readLine() throws IOException{
String string = bReader.readLine();
if(string == null){
return null;
}
string = count + string;
count++;
return string;
}
}

浙公网安备 33010602011771号