浅谈 java 设计模式--装饰模式(Decorator pattern)
2012-08-15 16:20
876 查看
装饰模式又称包装(Wrapper)模式,是以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。对客户端透明意味着接口不变。
问题:
在OO设计和开发过程中,经常会遇到下面的情况:我们需要为已经设计好的类添加新的职责,通常情况下我们会定义一个新类继承自定义好的类.由于组合比继承更好(复杂度高,继承深度深等原因,见<设计模式解析>P39讨论),今天我们就来介绍一下应用的组合的装饰模式.
总结:
装饰模式将更多的功能动态地附加到一个对象上。对功能扩展而言,装饰模式提供了一个灵活的、可以替代继承的选择。
问题:
在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(); } }
总结:
装饰模式将更多的功能动态地附加到一个对象上。对功能扩展而言,装饰模式提供了一个灵活的、可以替代继承的选择。
相关文章推荐
- Java设计模式十九:装饰模式(Decorator Pattern)
- Java设计模式十九:装饰模式(Decorator Pattern)
- JAVA设计模式之 装饰模式【Decorator Pattern】
- 基于东北F4的设计模式情景剧——第一幕 装饰模式(Decorator Pattern)
- java IO包 与 装饰设计模式 浅谈
- 设计模式(三)The Decorator Pattern 装饰器模式
- Java之装饰模式(Decorator Pattern)
- Java设计模式之装饰模式(Decorator模式)介绍
- java中装饰设计模式(decorator)
- Java开发中的23种设计模式之七:装饰模式(Decorator)
- Java设计模式-装饰者模式(Decorator Pattern)
- 浅谈 java 设计模式--构建模式(Builder pattern)
- 设计模式十 之 装饰器模式(Decorator Pattern)
- java设计模式之装饰器模式(Decorator)
- android设计模式-装饰模式(Decorator Pattern)
- 小鸦之设计模式(4) - 装饰模式Decorator pattern
- JAVA设计模式(7) —<结构型>装饰模式(Decorator)
- .NET设计模式(10):装饰模式(Decorator Pattern)
- 模式人生-从生活中的点点滴滴认识设计模式1-装饰器模式(Decorator Pattern)
- 极速理解设计模式系列:23.装饰器模式(Decorator Pattern)