Decorator Pattern [GoF]



Similar documents
INPUT AND OUTPUT STREAMS

The Java I/O System. Binary I/O streams (ascii, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

WRITING DATA TO A BINARY FILE

Principles of Software Construction: Objects, Design, and Concurrency. Design Case Study: Stream I/O Some answers. Charlie Garrod Jonathan Aldrich

Software Architectures

CS 1302 Ch 19, Binary I/O

Today s Outline. Computer Communications. Java Communications uses Streams. Wrapping Streams. Stream Conventions 2/13/2016 CSE 132

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

Java Network Programming. The java.net package contains the Socket class. This class speaks TCP (connection-oriented protocol).

What is an I/O Stream?

Stream Classes and File I/O

Files and input/output streams

! "# $%&'( ) * ).) "%&' 1* ( %&' ! "%&'2 (! ""$ 1! ""3($

AVRO - SERIALIZATION

1 of 1 24/05/ :23 AM

JAVA - FILES AND I/O

Mail User Agent Project

Building a Multi-Threaded Web Server

Readings and References. Topic #10: Java Input / Output. "Streams" are the basic I/O objects. Input & Output. Streams. The stream model A-1.

CS506 Web Design and Development Solved Online Quiz No. 01

ABSTRACT FACTORY AND SINGLETON DESIGN PATTERNS TO CREATE DECORATOR PATTERN OBJECTS IN WEB APPLICATION

This example illustrates how to copy contents from one file to another file. This topic is related to the I/O (input/output) of

public static void main(string[] args) { System.out.println("hello, world"); } }

D06 PROGRAMMING with JAVA

Scalable Computing with Hadoop

Introduction to Object-Oriented Programming

Chapter 10. A stream is an object that enables the flow of data between a program and some I/O device or file. File I/O

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Logging in Java Applications

Contents. 9-1 Copyright (c) N. Afshartous

Fundamentals of Java Programming

How To Write A Map In Java (Java) On A Microsoft Powerbook 2.5 (Ahem) On An Ipa (Aeso) Or Ipa 2.4 (Aseo) On Your Computer Or Your Computer

Programming in Java

RMI Client Application Programming Interface

5 HDFS - Hadoop Distributed System

When the transport layer tries to establish a connection with the server, it is blocked by the firewall. When this happens, the RMI transport layer

Socket Programming in Java

Amazon Glacier. Developer Guide API Version

Hadoop at Yahoo! Owen O Malley Yahoo!, Grid Team owen@yahoo-inc.com

13 File Output and Input

Learning Outcomes. Networking. Sockets. TCP/IP Networks. Hostnames and DNS TCP/IP

Web Development in Java

Patterns in. Lecture 2 GoF Design Patterns Creational. Sharif University of Technology. Department of Computer Engineering

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

Java CPD (I) Frans Coenen Department of Computer Science

System Calls and Standard I/O

Lecture 7: Class design for security

11 November

1 Step 1: Select... Files to Encrypt 2 Step 2: Confirm... Name of Archive 3 Step 3: Define... Pass Phrase

Java SE 8 Programming

Programming Methods & Java Examples

SSO Eurécia. and external Applications. Purpose

Stack Allocation. Run-Time Data Structures. Static Structures

Communicating with a Barco projector over network. Technical note

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

Transparent Redirection of Network Sockets 1

AP Computer Science Java Subset

MCI-Java: A Modified Java Virtual Machine Approach to Multiple Code Inheritance

JAVA IN A NUTSHELL O'REILLY. David Flanagan. Fifth Edition. Beijing Cambridge Farnham Köln Sebastopol Tokyo

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime?

Java Network. Slides prepared by : Farzana Rahman

Hadoop WordCount Explained! IT332 Distributed Systems

Structural Design Patterns Used in Data Structures Implementation

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

ACM Crossroads Student Magazine The ACM's First Electronic Publication

Introduction to Parallel Programming and MapReduce

Creating a Simple, Multithreaded Chat System with Java

Java from a C perspective. Plan

Lecture J - Exceptions

Servlets. Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun

An Introduction To UML Class Diagrams Classes

Copy the.jar file into the plugins/ subfolder of your Eclipse installation. (e.g., C:\Program Files\Eclipse\plugins)

COMPUTER SCIENCE. Paper 1 (THEORY)

Java (12 Weeks) Introduction to Java Programming Language

Syllabus for CS 134 Java Programming

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Tutorial Reference Manual. Java WireFusion 4.1

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Specialized Programme on Web Application Development using Open Source Tools

Streaming Lossless Data Compression Algorithm (SLDC)

Java Interview Questions and Answers

An Overview of Java. overview-1

COSC 6397 Big Data Analytics. Distributed File Systems (II) Edgar Gabriel Spring HDFS Basics

Advanced Java Client API

CS193j, Stanford Handout #10 OOP 3

Génie Logiciel et Gestion de Projets. Patterns

Multiple vulnerabilities in Apache Foundation Struts 2 framework. Csaba Barta and László Tóth

Object Oriented Databases. OOAD Fall 2012 Arjun Gopalakrishna Bhavya Udayashankar

File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files

Step 4: Configure a new Hadoop server This perspective will add a new snap-in to your bottom pane (along with Problems and Tasks), like so:

Transcription:

Decorator Pattern [GoF] Intent Attach additional capabilities to objects dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. Also Known As Wrapper. Motivation Suppose you have a class that allows an application to write data to a file: public class FileOutputStream { public FileOutputStream(String name); public write(byte[] data); public void flush(); public void close(); Imaging that the same or another application generates large data to be saved on disk. You decide to introduce another class that compresses the data: Design Patterns Decorator Pattern [GoF] 1

public class DeflatorFileOutputStream extends FileOutputStr. { public void write(byte[] data); Yet other applications may require additional responsibilities for writing data to files: some want to URL-encode strings before saving them on disk some want to create a digest (hash code) generated from the original data, and append it to the data to be saved on disk Thus, you might end up with a polluted class hierarchy: FileOutputStream DeflatorFileOutputStream DigestFileOutputStream... DeflatorFileOutputStream WithDigest Design Patterns Decorator Pattern [GoF] 2

A more flexible strategy for achieving the required responsibility is to use object composition: You enclose the an object with a given responsibility into another one which adds additional responsibilities. For example, a FileOutputStream object has the responsibility to save data on disk. In order to save data in a compressed way, compress it first by using a DeflatorOutputStream object which possesses the deflating responsibility only: write write adeflatoroutputstream afileoutputstream The client first creates a FileOutputStream object, and then encapsulates it with a DeflatorOutputStream object. Then, the client uses the DeflatorOutputStream object as it were merely a FileOutputStream object. The DeflatorOutputStream object is a sort of decorator for the FileOutputStream object. However, it must be ensured that both objects provide the same interface. In addition, the decorating object must delegate its method invocations sooner or later to the decorated object. Design Patterns Decorator Pattern [GoF] 3

This can be achieved by introducing the following class structure: 1 OutputStream FileOutputStream FilterOutputStream 1 DigestOutputStream DeflatorOutputStream OutputStream is an abstract class for all kind of output stream objects. It defines the common interface for (output) stream-related methods such as several versions of write, flush, and close. FilterOutputStream is a concrete (or abstract) class, the so-called decorator, that simply forwards any OutputStream method to its delegate, an OutputStream object. Subclasses of FilterOutputStream can extend the behavior of the methods inherited by FilterOutputStream. Design Patterns Decorator Pattern [GoF] 4

In addition, decorator subclasses are free to add specific functionality. For example, class DeflatorOutputStream may allow clients to call the finish method which finalizes the compression of data without closing the output stream. Applicability Use the Decorator pattern to add responsibilities to individual objects dynamically and transparently. for responsibilities that can be withdrawn. when extension by subclassing is impractical. Design Patterns Decorator Pattern [GoF] 5

Structure Component method 1 ConcreteCompontent method Decorator component method 1 component.method() ConcreteDecoratorA addedstate1 method ConcreteDecoratorB addedstate method addedbehavior addedbehavior(); super.method(); Design Patterns Decorator Pattern [GoF] 6

Participants Component (OutputStream) defines the interface for objects that can have capabilities added to them ConcreteComponent (FileOutputStream) defines an object to which additional capabilities can be attached Decorator maintains a reference to a Component object and defines an interface that conforms to Component s interface ConcreteDecorator (DeflatorOutputStream, DigestOutputStream) adds capabilities to the component Collaborations Decorator forwards requests to its Component object. It may optionally perform additional operations before and after forwarding the request. Consequences More flexible than static inheritance. Avoids feature-laden classes high up in the hierarchy. A Decorator and its Component aren t identical. Lots of little objects. Design Patterns Decorator Pattern [GoF] 7

Implementation A Decorator object s interface must conform to the interface of the component it decorates. ConcreteDecorator classes must inherit from a common class. Class Decorator can be made concrete when you need only to add one responsibility. Keep Component class lightweight. Decorator pattern is an alternative to the Strategy pattern: The decorator allows to change an object s behavior by wrapping the original object with a decorator. By contrast, with the Strategy pattern an object s behavior is changed by replacing a strategy object (which is not visible by the client) by another strategy object. Sample Code The following sample code illustrates the use of the Decorator pattern. We give sketches of Java s java.io package. We start with the abstract class OutputStream: Design Patterns Decorator Pattern [GoF] 8

public abstract class OutputStream { public abstract void write(int b) throws IOException; public void write(byte b[]) throws IOException { write(b, 0, b.length); public void write(byte b[], int off, int len) throws IOException { // Perform some sanity checks. If OK then // write each byte in the byte array: for (...) write(b[some_index]); public void flush() throws IOException { public void close() throws IOException { Design Patterns Decorator Pattern [GoF] 9

Class FileOutputStream writes data to files. Details are not given: public class FileOutputStream extends OutputStream { // Implements and/or overwrites the methods of // class OutputStream. // In addition, some additional, class-specific // methods are here, too. Design Patterns Decorator Pattern [GoF] 10

Class FilterOutputStream is the decorator base class. It defines the default behavior of decorators. (Due to methodological reasons, class FilterOutputStream has been simplified.) public class FilterOutputStream extends OutputStream { private OutputStream out; public FilterOutputStream(OutputStream out) { this.out = out; public void write(int b) throws IOException { out.write(b); public void write(byte b[]) throws IOException { out.write(b, 0, b.length); public void write(byte b[], int off, int len) throws IOException { out.write(b, off, len); public void flush() throws IOException { out.flush(); public void close() throws IOException { out.flush(); Design Patterns Decorator Pattern [GoF] 11

Classes DeflatorOutputStream and DigestOutputStream are decorator subclasses. A sketch of DeflatorOutputStream is given next: public class DeflatorOutputStream extends FilterOutputStream { protected byte[] buf; protected Deflator deflator; public DeflatorOutputStream(OutputStream os, Deflator d); public void write(byte[] b, int off, int len) throws IOException; public void write(int b) throws IOException; public void close() throws IOException; public void finish() throws IOException; protected void deflate() throws IOException; Design Patterns Decorator Pattern [GoF] 12

An application wanting to store text strings as URL-encoded strings may use an URL encoding filter: public class UrlEncodeOutputStream extends FilterOutputStream { // Use class java.net.urlencoder to encode String // objects, left as an exercise. // Provide a method public void writestring(string s). The application then can store text to disk in URL-encoded and deflated form: Deflator defl =...; UrlEncodeOutputStream os = new UrlEncodeOutputStream( new DeflatorOutputStream( new FileOutputStream("file"), defl)); String s =...; // string that must become URL-encoded os.writestring(s); Design Patterns Decorator Pattern [GoF] 13

Related Patterns Adapter: A decorator is different from an adapter in that a decorator only changes an object s responsibility, not its interface. Strategy: A decorator lets you change the skin; a strategy lets you change the interior. Design Patterns Decorator Pattern [GoF] 14