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

装饰模式又称包装(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();
      }
} 

总结:

装饰模式将更多的功能动态地附加到一个对象上。对功能扩展而言,装饰模式提供了一个灵活的、可以替代继承的选择。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值