您的位置:首页 > 编程语言 > Java开发

浅谈 java 设计模式--装饰模式(Decorator pattern)

2012-08-15 16:20 876 查看
装饰模式又称包装(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();
}
}

总结:

装饰模式将更多的功能动态地附加到一个对象上。对功能扩展而言,装饰模式提供了一个灵活的、可以替代继承的选择。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: