《Java与模式》学习笔记之三-----装饰(Decorator)模式

来源:互联网 发布:java人事管理系统 编辑:程序博客网 时间:2024/04/30 09:37

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

       }

}

 

总结:

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

本书中451页的发票系统的例子,好!