装饰者模式

定义:动态地给一个对象添加一些额外的职责。就增加功能来说,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();
		}
	}
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值