`
0428loveyu
  • 浏览: 30918 次
  • 性别: Icon_minigender_2
  • 来自: 西安
文章分类
社区版块
存档分类
最新评论

Decorator Design Pattern

 
阅读更多

To extend or modify the behaviour of ‘an instance’ at runtime decoratordesign patternis used. Inheritance is used to extend the abilities of ‘a class’. Unlike inheritance, you can choose any single object of a class andmodify its behaviourleaving the other instances unmodified.

In implementing the decorator pattern you construct a wrapper around an object by extending its behavior. The wrapper will do its job before or after and delegate the call to the wrapped instance.

Design of decorator pattern

You start with aninterfacewhich creates a blue print for the class which will have decorators. Then implement that interface with basic functionalities. Till now we have got an interface and an implementation concrete class. Create anabstract classthat contains (aggregation relationship) an attribute type of the interface. The constructor of this class assigns the interface type instance to that attribute. This class is the decorator base class. Now you can extend this class and create as many concrete decorator classes. The concrete decorator class will add its own methods. After / before executing its own method the concrete decorator will call the base instance’s method. Key to this decorator design pattern is the binding of method and the base instance happens at runtime based on the objectpassed as parameterto the constructor. Thus dynamically customizing the behavior of that specific instance alone.

Decorator Design Pattern – UML Diagram


Implementation of decorator pattern

Following given example is an implementation of decorator design pattern. Icecream is a classic example for decorator design pattern. You create a basic icecream and then add toppings to it as you prefer. The added toppings change the taste of the basic icecream. You can add as many topping as you want. This sample scenario is implemented below.

package com.javapapers.sample.designpattern;
public interface Icecream {
public String makeIcecream();
}
The above is an interface depicting an icecream. I have kept things as simple as possible so that the focus will be on understanding the design pattern. Following class is a concrete implementation of this interface. This is the base class on which the decorators will be added.

package com.javapapers.sample.designpattern;
public class SimpleIcecream implements Icecream {
@Override
public String makeIcecream() {
return "Base Icecream";
}
}

Following class is the decorator class. It is the core of the decorator design pattern. It contains an attribute for the type of interface. Instance is assigned dynamically at the creation of decorator using its constructor. Once assigned that instance method will be invoked.

package com.javapapers.sample.designpattern;
abstract class IcecreamDecorator implements Icecream {
protected Icecream specialIcecream;
public IcecreamDecorator(Icecream specialIcecream) {
this.specialIcecream = specialIcecream;
}
public String makeIcecream() {
return specialIcecream.makeIcecream();
}
}

Following two classes are similar. These are two decorators, concrete class implementing the abstract decorator. When the decorator is created the base instance is passed using the constructor and is assigned to the super class. In the makeIcecream method we call the base method followed by its own method addNuts(). This addNuts() extends the behavior by adding its own steps.

package com.javapapers.sample.designpattern;
public class NuttyDecorator extends IcecreamDecorator {
public NuttyDecorator(Icecream specialIcecream) {
super(specialIcecream);
}
public String makeIcecream() {
return specialIcecream.makeIcecream() + addNuts();
}
private String addNuts() {
return " + cruncy nuts";
}
}
package com.javapapers.sample.designpattern;
public class HoneyDecorator extends IcecreamDecorator {
public HoneyDecorator(Icecream specialIcecream) {
super(specialIcecream);
}
public String makeIcecream() {
return specialIcecream.makeIcecream() + addHoney();
}
private String addHoney() {
return " + sweet honey";
}
}

Execution of the decorator pattern

I have created a simple icecream and decorated that with nuts and on top of it with honey. We can use as many decorators in any order we want. This excellent flexibility and changing the behaviour of an instance of our choice at runtime is the main advantage of the decorator design pattern.

package com.javapapers.sample.designpattern;
public class TestDecorator {
public static void main(String args[]) {
Icecream icecream = new HoneyDecorator(new NuttyDecorator(new SimpleIcecream()));
System.out.println(icecream.makeIcecream());
}
}

Output

Base Icecream + cruncy nuts + sweet honey

Decorator Design Pattern in java API

java.io.BufferedReader;
java.io.FileReader;
java.io.Reader;

The above readers of java API are designed using decorator design pattern.

本文转载自:http://javapapers.com/design-patterns/decorator-pattern/版权所有
分享到:
评论

相关推荐

    design pattern

    在给定的压缩包文件中,包含了九种经典的设计模式示例,它们分别是:单例模式(Singleton)、策略模式(StrategyPattern)、适配器模式(AdapterPattern)、装饰者模式(DecoratorPattern)、抽象工厂模式...

    美团Java 岗 154 道面试题.zip

    102.举一个用 Java 实现的装饰模式(decorator design pattern)?它是作用于对象层次还是类层次? 103.在 Java 中,为什么不允许从静态方法中访问非静态变量? 104.设计一个 ATM 机,请说出你的设计思路?

    Design*Pattern*Framework*4.5

    "Design*Pattern*Framework*4.5" 可能指的是一个基于 .NET Framework 4.5 的设计模式实现或教程集合。 设计模式是经验丰富的软件开发者的智慧结晶,它们被分为三类:创建型、结构型和行为型。创建型模式涉及对象的...

    Design Pattern - Decorator

    装饰器模式(Decorator Pattern)是一种结构型设计模式,它允许在运行时给对象添加新的行为或职责,同时保持对象的接口不变。这种模式的核心在于,它动态地将责任附加到对象上,通过将对象包装在一个装饰类中来扩展...

    C++设计模式(Design Pattern)范例源代码

    23种设计模式(Design Pattern)的C++实现范例,包括下面列出的各种模式,代码包含较详细注释。另外附上“设计模式迷你手册.chm”供参考。 注:项目在 VS2008 下使用。 创建型: 抽象工厂模式(Abstract Factory) 生成...

    设计模式源码Head_First_DesignPattern_src

    在本文中,我们将深入探讨设计模式的核心概念,并结合"Head First DesignPattern_src"中的源码,详细解析一些关键的设计模式。 1. 单例模式(Singleton): 单例模式确保一个类只有一个实例,并提供全局访问点。在...

    Head First Design Pattern

    2. 结构型设计模式:包括适配器模式(Adapter)、装饰器模式(Decorator)、代理模式(Proxy)、桥接模式(Bridge)、组合模式(Composite)、外观模式(Facade)和享元模式(Flyweight)。这些模式关注如何将类和...

    designpattern.zip

    本资源"designpattern.zip"包含了对Java中23种经典设计模式的详细讲解和代码实例,对于中高级Java工程师来说,是提升开发技能的必备学习材料。 设计模式通常分为创建型、结构型和行为型三大类。创建型设计模式关注...

    design pattern tutorial

    10. 装饰器模式(Decorator Pattern):动态地给一个对象添加一些额外的职责。它提供了一种灵活的扩展一个对象功能的方式,而不需要使用继承。 11. 外观模式(Facade Pattern):提供了一个统一的接口,用来访问子...

    JAVA software design pattern

    7. **装饰器模式(Decorator)**:动态地给对象添加一些额外的职责,提供一种比继承更灵活的方式来扩展功能。 8. **代理模式(Proxy)**:为其他对象提供一种代理以控制对这个对象的访问。常用于远程代理、虚拟代理...

    Software Architecture Design Pattern In Java

    3. **装饰器模式(Decorator Pattern)**: - 定义:动态地给一个对象添加一些额外的职责。 - 应用场景:可以用来扩展功能而不改变原有类的结构,如网络通信中的数据加密解密。 4. **观察者模式(Observer ...

    DesignPattern.zip

    "DesignPattern.zip"这个压缩包包含了使用C++语言实现的设计模式源代码,适合在Visual Studio 2017环境下编译运行,并且能够方便地移植到Linux平台。下面将对设计模式及其在C++中的应用进行详细阐述。 1. **单例...

    Java Magazine NovemberDecember 2018.pdf

    此外,"Java Present and Future"、"The Decorator Design Pattern in Depth"、"Fix This" 等文章深入探讨了Java的不同方面,如装饰者设计模式的深入分析,以及提供给中高级测试问题的"Fix This"部分。 整体上,...

    design pattern中文版

    "Design Pattern中文版" 提供的是这些经典设计模式的中文解释,使得中国的开发者能够更方便地理解和应用这些模式。这份资料的描述指出字迹清晰,意味着阅读体验良好,适合深入学习。 PDF格式是一种广泛使用的文档...

    Professional ASP.NET Design Pattern 源代码

    《Professional ASP.NET Design Pattern》是一本深入探讨ASP.NET开发中设计模式的专业书籍,源代码的提供使得读者能够更直观地理解和应用这些设计模式。源代码的分章节组织(如c07到c14)表明内容可能按照书中的章节...

    Gof design pattern 中文/英文版+web+学习笔记

    7. **装饰器模式(Decorator)**:动态地给一个对象添加一些额外的职责。装饰器模式允许在运行时为对象添加新功能,同时保持接口不变。 8. **适配器模式(Adapter)**:将一个类的接口转换成客户希望的另一个接口。...

    design pattern PPT

    设计模式(Design Pattern)是软件工程中用于解决软件设计问题的既定方案。设计模式并非直接的代码实现,而是一套被验证过的通用解决方案模板。它们是由经验丰富的软件开发者总结出的,在特定上下文中对常见问题的...

    Swift DesignPattern

    本资料"Swift DesignPattern"包含了一些Swift语言中的常见设计模式实例,下面我们将详细探讨这些设计模式及其在Swift中的应用。 1. **单例模式(Singleton)**:单例模式确保一个类只有一个实例,并提供全局访问点...

    the code of Design Pattern

    在“designpattern”这个压缩包中,可能包含了各种设计模式的C++实现。比如,单例模式通常用来保证一个类只有一个实例,并提供全局访问点;工厂方法模式则允许子类决定实例化哪一个类,提供了一种封装对象创建过程的...

Global site tag (gtag.js) - Google Analytics