装饰模式又称包装(Wrapper)模式,是以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。对客户端透明意味着接口不变。
问题:
在OO设计和开发过程中, 经常会遇到下面的情况: 我们需要为已经设计好的类添加新的职责, 通常情况下我们会定义一个新类继承自定义好的类. 由于组合比继承更好(复杂度高,继承深度深等原因, 见<设计模式解析>P39讨论), 今天我们就来介绍一下应用的组合的装饰模式.
类图:
源代码:
package com.designpatterns.decorator;
/**
* 抽象接口,规范准备接收附加责任的对象
* @author suki
*/
public interface Component {
void operation();
}
/**
* 接收附加责任, 此类型的类可以有多个, 只对应一个Decorator类
* @author suki
*/
public class ConcreteComponent implements Component{
public ConcreteComponent(){}
public void operation()
{
System.out.println("ConcreteComponent.operation()");
}
}
/**
* 装饰角色,持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口
* @author suki
*/
public class Decorator implements Component {
private Component component;
public Decorator(){}
public Decorator(Component component)
{
this.component = component;
}
public void operation() {
component.operation();
}
}
/**
* 添加附加责任
* @author suki
*/
public class ConcreteDecorator extends Decorator {
public ConcreteDecorator(){}
public ConcreteDecorator(Component component)
{
super(component);
}
public void operation()
{
super.operation();
this.addedOperation();
}
public void addedOperation()
{
System.out.println("ConcreteDecorator.addedOperation()");
}
}
/**
* 客户端类
* @author suki
*/
public class Client {
public static void main(String[] args) {
Component component = new ConcreteComponent();
Decorator decorator = new ConcreteDecorator(component);
//客户端不变, 但已增加了责任
decorator.operation();
}
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/surprisesdu/archive/2006/02/22/605965.aspx