COMP 121 Week 12: Decorator and Adapter Design Patterns.

Slides:



Advertisements
Similar presentations
I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
Advertisements

COMP 121 Week 9: AbstractList and ArrayList. Objectives List common operations and properties of Lists as distinct from Collections Extend the AbstractCollection.
Decorator Pattern Applied to I/O stream classes. Design Principle Classes should be open for extension, but closed for modification –Apply the principle.
Matt Klein. Decorator Pattern  Intent  Attach Additional responsibilities to an object by dynamically. Decorators provide a flexible alternative to.
02 - Structural Design Patterns – 1 Moshe Fresko Bar-Ilan University תשס"ח 2008.
Design Patterns CMPS Design Patterns Consider previous solutions to problems similar to any new problem ▫ must have some characteristics in common.
Computer Science 209 Software Development Iterators.
Geoff Holmes Overview IO Zoo Stream I/O File I/O Buffering Random-Access Text Streams Examples Serialization Java IO – programs that start with import.
Design Patterns Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Design Patterns. CS351 - Software Engineering (AY2007)Slide 2 Behavioral patterns Suppose we have an aggregate data structure and we wish to access the.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
ADAPTER PATTERN Ali Zonoozi Design patterns course Advisor: Dr. Noorhoseini Winter 2010.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
Proxy Design Pattern Source: Design Patterns – Elements of Reusable Object- Oriented Software; Gamma, et. al.
Design Patterns.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
SE2811 Week 7, Class 1 Composite Pattern Applications Conceptual form Class structure Coding Example Lab Thursday: Quiz SE-2811 Slide design: Dr. Mark.
Design Pattern. The Observer Pattern The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all.
Go4 Visitor Pattern Presented By: Matt Wilson. Introduction 2  This presentation originated out of casual talk between former WMS “C++ Book Club” (defunct.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Session 21 Chapter 10: Mechanisms for Software Reuse.
Object Persistence and Object serialization CSNB534 Asma Shakil.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Decorator Explained. Intent Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub-classing for.
SDP Structural Pattern. SDP-2 Structural Patterns Concerned with how classes and objects are composed to form large structures Class Patterns use.
Decorator Design Pattern Rick Mercer CSC 335: Object-Oriented Programming and Design.
By Shishir Kumar Contact:
Structural Design Patterns
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns IV Structural Patterns.
(c) University of Washington16-1 CSC 143 Java Lists via Links Reading: Ch. 23.
CS 210 Final Review November 28, CS 210 Adapter Pattern.
Class & Object Adapter Patterns (with a focus on Class Adapter) Tim Gutowski CSPP 51023, Winter 2008.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
– Advanced Programming P ROGRAMMING IN Lecture 22 Input and Output System.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Adapter and Façade Patterns By Wode Ni and Leonard Bacon-Shone.
Lecture 14 Inheritance vs Composition. Inheritance vs Interface Use inheritance when two objects share a structure or code relation Use inheritance when.
Bridge Bridge is used when we need to decouple an abstraction from its implementation so that the two can vary independently. This type of design pattern.
Example to motivate discussion We have two lists (of menu items) one implemented using ArrayList and another using Arrays. How does one work with these.
Decorator Design Pattern Rick Mercer CSC 335: Object-Oriented Programming and Design.
Proxy Pattern defined The Proxy Pattern provides a surrogate or placeholder for another object to control access to it by creating a representative object.
Watching the movie the hard way…. Page 256 – Head First Design Patterns.
S.Ducasse Stéphane Ducasse 1 Decorator.
The Decorator Pattern (Structural) ©SoftMoore ConsultingSlide 1.
CS 210 Proxy Pattern Nov 16 th, RMI – A quick review A simple, easy to understand tutorial is located here:
More Patterns CS 124. More Basic Patterns Patterns you’ve already seen (without knowing it) Observer / Listener Wrapper Composite Decorator / Filter Patterns.
Topic 13 Iterators. 9-2 Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over.
1 Putting Streams to use. 2 Stream Zoo C++ gives you istream, ostream, iostream, ifstream, ofstream, fstream, wistream, wifstream, istrsteam… (18) Java.
S.Ducasse Stéphane Ducasse 1 Adapter.
COMPOSITE PATTERN NOTES. The Composite pattern l Intent Compose objects into tree structures to represent whole-part hierarchies. Composite lets clients.
Design Patterns: Brief Examples
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University
Adapter Design Pattern
I/O Basics.
7. Decorator, Façade Patterns
Java Programming Language
08/15/09 Design Patterns James Brucker.
Object Oriented Design Patterns - Structural Patterns
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Structural Patterns: Adapter and Bridge
Introduction to Design Patterns
7. Decorator SE2811 Software Component Design
Fundaments of Game Design
Decorator.
CS 240 – Advanced Programming Concepts
Decorator Pattern.
Presentation transcript:

COMP 121 Week 12: Decorator and Adapter Design Patterns

Decorator Design Pattern Intent: augment objects with new responsibilities Use when: –Extension by subclassing is impractical (want to add responsibilities to individual objects, not an entire class) –Responsibilities can be withdrawn Decorator implements the same interface as the object it decorates A "shell" or "wrapper" around an object –Requests that come in to the decorator are "forwarded" to the object it decorates

Decorator Design Pattern (cont’d) The key to a successful Decorator is to have a set of objects defined by an interface Decorator implements the interface and takes an object of that interface type as a parameter of its constructor, which it saves internally When a method is called on the decorator: –May do some pre-processing before calling the same method on the decorated object –May do some post-processing on the results returned from the same method in the decorated object

Why Use a Decorator Pattern More flexibility than inheritance –Responsibilities can be added or removed at runtime) Avoids feature-laded classes high up in the hierarchy A "pay-as-you-go" approach to adding responsibilities –Can define a simple class –Add functionality incrementally with decorators

Decorator Example 1: Sunglasses People “decorate” themselves in many different ways (for example clothing, makeup, jewelry, glasses) Sunglasses intercept incoming light and provide modified light to the eyes –The eyes still get basically the same type of input (stream of light into the eyes) –Input (light) is transformed by the sunglasses, but is still a form of light (not converted into sound or smell) Eyes take in light whether or not the decorator (pair of sunglasses) is present –This “transparent” property of Decorator is what allows Decorators to be chained together –Person may wear contact lenses AND sunglasses

Decorator Example 2: Audio Enhancers/Filters Electronic devices or software can be used to enhance, morph, or disguise your voice –Change vocal pitch and timbre or apply other effects such as volume or vibrato Filter changes the audio stream –Input is an audio stream –Output is an audio stream Audio may be passed through a series of filters to get the sound qualities desired –Chain of decorators Used with musical instruments, too

Decorator Example 3: Java File I/O Basic I/O classes are InputStream, OutputStream, Reader and Writer Need to add behaviors to the stream to get the desired results –BufferedInputStream adds buffering for performance –DataInputStream adds input of primitive data types FileInputStream in = new FileInputStream("test.dat"); BufferedInputStream bin = new BufferedInputStream(in); DataInputStream dbin = new DataInputStream(bin);

Decorator Example 4: Unmodifiable Collection List products = new ArrayList (); products.add(new Product("Book")); products.add(new Product("Game")); Collection readOnlyProducts = new UnmodifiableCollection (products); new UnmodifiableCollection (products); Product p = readOnlyProducts.get(1); // returns Game readOnlyProducts.add(new Product(...)); // Throws exception products.add(new Product("Puzzle")); int numProducts = readOnlyProducts.size(); // returns 3

public class CollectionDecorator implements Collection { protected Collection coll; protected Collection coll; public CollectionDecorator(Collection c) { public CollectionDecorator(Collection c) { coll = c; coll = c; } public boolean add(E obj) { public boolean add(E obj) { return coll.add(obj); return coll.add(obj); } public int size() { public int size() { return coll.size(); return coll.size(); } // Other methods similar // Other methods similar}

public class IteratorDecorator implements Iterator { protected Iterator iter; protected Iterator iter; public IteratorDecorator(Iterator it) { public IteratorDecorator(Iterator it) { iter = it; iter = it; } public boolean hasNext() { public boolean hasNext() { return iter.hasNext(); return iter.hasNext(); } public E next() { public E next() { return iter.next(); return iter.next(); } public void remove() { public void remove() { iter.remove(); iter.remove(); }}

public class UnmodifiableCollection extends CollectionDecorator { public UnmodifiableCollection(Collection coll) { public UnmodifiableCollection(Collection coll) { super(coll); super(coll); } public boolean add(E obj) { public boolean add(E obj) { throw new UnsupportedOperationException("add not supported"); throw new UnsupportedOperationException("add not supported"); } // Similar implementation for all methods that would change contents // Similar implementation for all methods that would change contents public Iterator iterator() { public Iterator iterator() { return new UnmodifiableIterator (coll.iterator()); return new UnmodifiableIterator (coll.iterator()); }}

public class UnmodifiableIterator extends IteratorDecorator { public UnmodifiableIterator(Iterator iter) { public UnmodifiableIterator(Iterator iter) { super(iter); public void remove() { public void remove() { throw new UnsupportedOperationException("remove not supported"); throw new UnsupportedOperationException("remove not supported"); }}

Question: How does the Decorator design pattern differ from the Strategy design pattern?

Answer: The Decorator pattern changes the “skin” of an object –The decorator is a wrapper or outer layer that changes the behavior of an object –The object doesn’t know about its decorators The Strategy pattern changes the “guts” –The strategy is changed by using a different strategy object that alters or extends the behavior of an object –The object knows about the available strategies

Adapter Design Pattern Intent: –Convert the interface of a class into another interface that the clients expect –Lets classes work together that otherwise couldn't because of incompatible interfaces Use when: –You want to use an existing class and its interface doesn't match the one you need –You want to create a reusable class that cooperates with unrelated or unforeseen classes (classes that don't have compatible interfaces) Another type of “shell” or “wrapper” around an object –Requests that come in to the adapter are forwarded to the object being adapted, but the actual method being called is different

Adapter Example 1: Socket Wrench A socket attaches to a ratchet, provided that the size of the drive is the same Typical drive sizes in the United States are 1/2" and 1/4“ –A 1/2" drive ratchet will not fit into a 1/4" drive socket unless an adapter is used –A 1/2" to 1/4" adapter has a 1/2" female connection to fit on the 1/2" drive ratchet, and a 1/4" male connection to fit in the 1/4" drive socket

Adapter Example 2: Travel Adapter Kits In different parts of the world, different wattages and outlet types make it impossible to use personal appliances (shavers, hair dryers, etc.) without modification A travel adapter kit allows you to: –Plug your appliance into a converter to convert the wattage –Plug the converter into the wall outlet by adapting the plug type

Adapter Example 3: Replacing Legacy or 3rd Party Software The adapter pattern is commonly used in applications where some third party software is being replaced with some other software Rather than rewrite the application to use the new software interface, use an adapter to adapt the old interface to the new interface: –The application code calls the old interface, but is now making those requests via the adapter –The adapter converts the requests to requests that are compatible with the new software –The adapter may do some pre- or post-processing in order to adapt request

Adapter Code Example public class Product { public Sku getSku() { public Sku getSku() { return sku; return sku; } public void setSku(Sku sku) { public void setSku(Sku sku) { this.sku = sku; this.sku = sku; } public Money getCost() { public Money getCost() { return cost; return cost; } public void setCost(Money cost) { public void setCost(Money cost) { this.cost = cost; this.cost = cost; } public Money calculatePrice() { … } public Money calculatePrice() { … } public Money calculateMarkup() { … } public Money calculateMarkup() { … }}

// We want to use this existing class in place of Product public class InventoryItem { private String barCode; private String barCode; private String itemName; private String itemName; private double purchasePrice; private double purchasePrice; private double salePrice; private double salePrice; public double sellsFor() { public double sellsFor() { return salesPrice; return salesPrice; } public String getBarCode() { public String getBarCode() { return barCode; return barCode; } // More methods here // More methods here}

public interface Product { Sku getSku(); Sku getSku(); void setSku(Sku sku); void setSku(Sku sku); Money getCost(); Money getCost(); void setCost(Money cost); void setCost(Money cost); Money calculatePrice(); Money calculatePrice(); Money calculateMarkup(); Money calculateMarkup(); // More methods… // More methods…}

public class InventoryItemToProductAdapter { private InventoryItem item; private InventoryItem item; public InventoryItemToProductAdapter(InventoryItem i) { public InventoryItemToProductAdapter(InventoryItem i) { item = i; item = i; } public void setCost(Money cost) { public void setCost(Money cost) { item.setPurchasePrice(cost); item.setPurchasePrice(cost); } public Money calculatePrice() { public Money calculatePrice() { return new Money(item.sellsFor()); return new Money(item.sellsFor()); } // More methods… // More methods…}

/* /* * Now that we have the adapter, we can add InventoryItem * Now that we have the adapter, we can add InventoryItem * objects to a list of products and treat them like any * objects to a list of products and treat them like any * other product * other product */ */ List products = new ArrayList (); List products = new ArrayList (); InventoryItem item = new InventoryItem(…); InventoryItem item = new InventoryItem(…); products.add(new InventoryItemToProductAdapter(item)); products.add(new InventoryItemToProductAdapter(item)); … // Having a half-off sale // Having a half-off sale for(Product product : products) { for(Product product : products) { product.setCost(product.getCost().div(2)); product.setCost(product.getCost().div(2)); }

Question? How does the Adapter design pattern differ from the Decorator design pattern?

Answer: The Decorator pattern only changes the object’s responsibilities, not its interface The Adapter pattern changes the object’s interface, often without changing its responsibilities

Questions?