定义:动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
结构图:
Component:
定义一个对象接口,可以给这些对象动态地添加职责。
public interface Component
{
void operation();
}
Concrete Component:
定义一个对象,可以给这个对象添加一些职责。
public class ConcreteComponent implements Component
{
public void operation()
{
// Write your code here
}
}
Decorator:
维持一个指向Component对象的引用,并定义一个与 Component接口一致的接口。
public class Decorator implements Component
{
public Decorator(Component component)
{
this.component = component;
}
public void operation()
{
component.operation();
}
private Component component;
}
Concrete Decorator:
在Concrete Component的行为之前或之后,加上自己的行为,以“贴上”附加的职责。
public class ConcreteDecorator extends Decorator
{
public void operation()
{
//addBehavior也可以在前面
super.operation();
addBehavior();
}
private void addBehavior()
{
//your code
}
}
模式的简化:
1. 如果只有一个Concrete Component类而没有抽象的Component接口时,可以让Decorator继承Concrete Component。
2. 如果只有一个Concrete Decorator类时,可以将Decorator和Concrete Decorator合并。
装饰模式在Java I/O库中的应用:
编写一个装饰者把所有的输入流内的大写字符转化成小写字符:
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
public class LowerCaseInputStream extends FilterInputStream
{
protected LowerCaseInputStream(InputStream in)
{
super(in);
}
@Override
public int read() throws IOException
{
int c = super.read();
return (c == -1 ? c : Character.toLowerCase((char) c));
}
@Override
public int read(byte[] b, int offset, int len) throws IOException
{
int result = super.read(b, offset, len);
for (int i = offset; i < offset + result; i++)
{
b[i] = (byte) Character.toLowerCase((char) b[i]);
}
return result;
}
}
测试我们的装饰者类:
import java.io.*;
public class InputTest
{
public static void main(String[] args) throws IOException
{
int c;
try
{
InputStream in = new LowerCaseInputStream(new BufferedInputStream(
new FileInputStream("D:\\test.txt")));
while ((c = in.read()) >= 0)
{
System.out.print((char) c);
}
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}