The Decorator Pattern (Structural) ©SoftMoore ConsultingSlide 1.

Slides:



Advertisements
Similar presentations
Decorator Pattern Applied to I/O stream classes. Design Principle Classes should be open for extension, but closed for modification –Apply the principle.
Advertisements

Chapter 3: The Decorator Pattern
Observer Method 1. References Gamma Erich, Helm Richard, “Design Patterns: Elements of Reusable Object- Oriented Software” 2.
Matt Klein. Decorator Pattern  Intent  Attach Additional responsibilities to an object by dynamically. Decorators provide a flexible alternative to.
1 Structural Design Patterns - Neeraj Ray. 2 Structural Patterns - Overview n Adapter n Bridge n Composite n Decorator.
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.
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
1 Patterns & GUI Programming Part 2. 2 Creating a Custom Layout Manager Layout manager determines how components are arranged/displayed in a container.
Design Patterns. CS351 - Software Engineering (AY2007)Slide 2 Behavioral patterns Suppose we have an aggregate data structure and we wish to access the.
ADAPTER PATTERN Ali Zonoozi Design patterns course Advisor: Dr. Noorhoseini Winter 2010.
Prototype Pattern Intent:
The Composite Pattern.. Composite Pattern Intent –Compose objects into tree structures to represent part-whole hierarchies. –Composite lets clients treat.
Design Patterns Module Name - Object Oriented Modeling By Archana Munnangi S R Kumar Utkarsh Batwal ( ) ( ) ( )
The Decorator Design Pattern (also known as the Wrapper) By Gordon Friedman Software Design and Documentation September 22, 2003.
Design Patterns.
1 Dept. of Computer Science & Engineering, York University, Toronto CSE3311 Software Design Adapter Pattern Façade pattern.
Department of Computer Science, York University Object Oriented Software Construction 16/09/ :52 PM 0 COSC3311 – Software Design Decorator Pattern.
Design Pattern. The Observer Pattern The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all.
BUILDER, MEDIATOR, AND DECORATOR Team 2 (Eli.SE).
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Decorator, Strategy, State Patterns.
Session 21 Chapter 10: Mechanisms for Software Reuse.
CS 151: Object-Oriented Design October 24 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
18 April 2005CSci 210 Spring Design Patterns 1 CSci 210.
Decorator Explained. Intent Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub-classing for.
Decorator Design Pattern Rick Mercer CSC 335: Object-Oriented Programming and Design.
COMP 121 Week 12: Decorator and Adapter Design Patterns.
Design Patterns CSIS 3701: Advanced Object Oriented Programming.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns IV Structural Patterns.
ECE450 - Software Engineering II1 ECE450 – Software Engineering II Today: Design Patterns VIII Chain of Responsibility, Strategy, State.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Strategy Pattern.
DESIGN PATTERNS COMMONLY USED PATTERNS What is a design pattern ? Defining certain rules to tackle a particular kind of problem in software development.
CPS Inheritance and the Yahtzee program l In version of Yahtzee given previously, scorecard.h held information about every score-card entry, e.g.,
Design Patterns Introduction
The Visitor Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
The Bridge Pattern (Structural) “All problems in computer science can be solved by another level of indirection.” – Butler Lampson ©SoftMoore ConsultingSlide.
The State Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Lecture 14 Inheritance vs Composition. Inheritance vs Interface Use inheritance when two objects share a structure or code relation Use inheritance when.
The Template Method Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1.
The Facade Pattern (Structural) ©SoftMoore ConsultingSlide 1.
The Prototype Pattern (Creational) ©SoftMoore ConsultingSlide 1.
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.
The Strategy Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
Decorator Design Pattern Rick Mercer CSC 335: Object-Oriented Programming and Design.
Watching the movie the hard way…. Page 256 – Head First Design Patterns.
S.Ducasse Stéphane Ducasse 1 Decorator.
Decorator Design Pattern Phillip Shin. Overview Problem Solution Example Key points.
The Flyweight Pattern (Structural) ©SoftMoore ConsultingSlide 1.
The Proxy Pattern (Structural) ©SoftMoore ConsultingSlide 1.
F-1 © 2007 T. Horton CS 4240 Principles of SW Design More design principles LSP, OCP, DIP, … And another pattern Decorator.
The Chain of Responsibility Pattern (Behavioral) ©SoftMoore ConsultingSlide 1.
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.
CLASSIFICATION OF DESIGN PATTERNS Hladchuk Maksym.
Design Patterns: MORE Examples
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University
Factory Patterns 1.
More Design Patterns 1.
More Design Patterns 1.
Decorator Intent Also known as Wrapper Example: a Text Window
Decorator Pattern Intent
Jim Fawcett CSE776 – Design Patterns Summer 2003
Object Oriented Design Patterns - Structural Patterns
Decorator Pattern Richard Gesick.
UNIT-III Structural Design Patterns
Structural Patterns: Adapter and Bridge
Decorator.
Decorator Pattern.
Software Design Lecture 10.
Presentation transcript:

The Decorator Pattern (Structural) ©SoftMoore ConsultingSlide 1

Motivating Example (Bob Tarr) Suppose that you have a GUI component such as a TextView, and you want to be able to add different kinds of properties such as borders and scrollbars. Assume the you have three types of borders (e.g., plain, fancy, and 3D) and two types of scrollbars (horizontal and vertical). Not every TextView object needs a border or a scrollbar, and a TextView object might need only one scrollbar, but not both. How can we design a solution that provides the flexibility to add borders and scrollbars? ©SoftMoore ConsultingSlide 2

Motivating Example (continued) Solution 1: Use inheritance. Inheritance is a static (compile-time) property. In order to provide a solution using inheritance, we would need class TextView plus 15 subclasses. –TextViewWithPlainBorder –TextViewWithFancyBorder –... –TextViewWith3DBorderVerticalHorizontalScrollbar Problems with Solution 1 –explosion of subclasses –choice of subclass to instantiate must be made at compile time –What if there were another type of behavior to TextView? ©SoftMoore ConsultingSlide 3

Motivating Example (continued) Solution 2: Use the Strategy pattern. Design the TextView class so that it can have different types of borders and scrollbars. This approach would not have the problems associated with Solution 1 –no class explosion –borders and/or scrollbars could be added at run-time. –easy to add new types of borders or variations on scrollbars (e.g., thin versus normal) ©SoftMoore ConsultingSlide 4

Motivating Example (continued) public class TextView extends Component { private Border border; private Scrollbar vsb; private Scrollbar hsb; public TextView(Border border, Scrollbar vsb, Scrollbar hsb) { this.border = border; this.vsb = vsb; this.hsb = hsb; } ©SoftMoore ConsultingSlide 5 (continued on next slide)

Motivating Example (continued) public TextView() { this(null, null, null); }... // set methods for borders and scrollbars ©SoftMoore ConsultingSlide 6 (continued on next slide)

Motivating Example (continued) public void draw() { if (border != null) border.draw(); if (vsb ! = null) vsb.draw(); if (hsb ! = null) hsb.draw();... // code to draw the TextView object } ©SoftMoore ConsultingSlide 7

Motivating Example (continued) Problem with Solution 2: Class TextView was modified so that it knew about borders and scrollbars. We could add different flavors of borders and scrollbars, but no other type of behavior; i.e., the types of behaviors that could be added to TextView were fixed at compile-time. If we wanted to add another type of behavior in addition to borders or scrollbars, we would need to modify TextView again. ©SoftMoore ConsultingSlide 8

Motivating Example (continued) Solution 3: Use the Decorator pattern. Instead of adding behaviors such as borders and scrollbars to a TextView object, using the decorator pattern you wrap the TextView object in one or more Decorator objects, and use those objects in the application. In effect, you add the TextView to its decorators. The TextView class knows nothing about its decorator objects, which makes it easy to add new types of behaviors to a TextView. ©SoftMoore ConsultingSlide 9

Motivating Example (continued) ©SoftMoore ConsultingSlide 10 Component TextView Structure of Solution 3 Decorator BorderScrollbar 1 PlainBorderFancyBorderThreeDBorderHScrollbarVScrollbar

Motivating Example (continued) public class TextView extends Component { public void draw() {... // code to draw the TextView object } ©SoftMoore ConsultingSlide 11 TextView knows nothing about borders and scrollbars.

Motivating Example (continued) public class FancyBorder extends Decorator { private Component component; public FancyBorder(Component component) { this.component = component; } public void draw() { component.draw(); // code to draw the FancyBorder } ©SoftMoore ConsultingSlide 12 Decorators need to know about components.

Motivating Example (continued) public class Client { public static void main(String[] args) { TextView plainTv = new TextView(); Component fbTv = new FancyBorder(plainTv); Component vsTv = new VScrollbar(fbTv); Component tv = new HScrollbar(vsTv); } ©SoftMoore ConsultingSlide 13 Client creates a plain TextView object and wraps it in the desire Decorator objects.

Strategy versus Decorator The Strategy pattern changes the “guts” of an object. –create component object –add strategy to component (component knows about its strategy) –client uses the component The Decorator pattern changes the “skin” of an object. –create component object –create decorator and add component to decorator (component does not know about its decorator) –client uses the decorator ©SoftMoore ConsultingSlide 14 : Client: Component: Strategy : Client: Decorator : Component

Decorator Pattern Intent: Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. Also Known As: Wrapper Applicability: Use the Decorator pattern –to add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects. –for responsibilities that can be withdrawn. –when extension by subclassing is impractical. Sometimes a large number of independent extensions are possible and would produce an explosion of subclasses to support every combination. Slide 15©SoftMoore Consulting

Decorator Pattern (continued) ©SoftMoore ConsultingSlide 16 1 Structure Component operation() ConcreteComponent operation() Decorator operation() ConcreteDecoratorA addedState operation() ConcreteDecoratorB operation() addedOperation()

Decorator Pattern (continued) Participants Component –defines the interface for objects that can have responsibilities added to them dynamically. ConcreteComponent –defines an object to which additional responsibilities can be attached. Decorator –maintains a reference to a Component object and defines an interface that conforms to Component’s interface. ConcreteDecorator –adds responsibilities to the component. Slide 17©SoftMoore Consulting

Decorator Pattern (continued) Collaborations Decorator forwards requests to its Component object. It may optionally perform additional operations before and after forwarding the request ©SoftMoore ConsultingSlide 18

Decorator Pattern (continued) Consequences (two benefits and two liabilities) The Decorator pattern provides a flexible alternative to inheritance. Whereas inheritance lets you add functionality to classes at compile time, decorators let you add functionality to objects at runtime Decorators you to add functionality incrementally as needed. An application doesn’t incur a penalty for features it doesn’t use. A decorator and its component aren’t identical. Don’t rely on object identity when using decorators. Decorators often results in lots of little objects. ©SoftMoore ConsultingSlide 19

Decorator Pattern (continued) Implementation A decorator object’s interface must conform to the interface of the component it decorates. There is no need to define an abstract decorator class when you need to add only one responsibility; e.g., when you are dealing with an existing class hierarchy rather than designing a new one. Just put the responsibility in the concrete Decorator. ©SoftMoore ConsultingSlide 20

Decorator Pattern (continued) Implementation (continued) To ensure a conforming interface, components and decorators must subclass a common Component class. It is important to keep this common class lightweight; otherwise the complexity of the Component class might make the decorators too heavyweight to use in quantity. Strategy might be a better choice than Decorator in situations where the Component class is intrinsically heavyweight. ©SoftMoore ConsultingSlide 21

Decorator Pattern in Java: Swing Java’s Swing GUI classes use decorators in a manner very similar to that described in the motivating example. Example 1 (from The Swing Tutorial) //In a container that uses a BorderLayout: JTextArea = new JTextArea(5, 30);... JScrollPane scrollPane = new JScrollPane(textArea);... add(scrollPane, BorderLayout.CENTER); Example 2 (David Geary) TableSortDecorator sortDecorator = new TableSortDecorator(table.getModel); table.setModel(sortDecorator); ©SoftMoore ConsultingSlide 22

Decorator Pattern in Java: I/O Basic I/O classes in Java provide minimal functionality. –classes InputStream and OutputStream for byte streams –classes Reader and Writer for character streams Additional behaviors can be added to an existing stream using the decorator pattern. –buffered stream –data stream (I/O of primitive types) –pushback stream (undo a read operation) The constructors for the byte stream classes take other byte streams as parameters, and similarly for the character stream classes. ©SoftMoore ConsultingSlide 23

Decorator Pattern in Java: I/O (continued) // create a basic file reader FileReader fRdr = new FileReader(data.txt); // add buffering and method readLine() // (uses a default-sized input buffer) BufferedReader bRdr = new BufferedReader(fRdr); // add capability to "unread" a character // or an array of characters PushbackReader pbRdr = new PushbackReader(bRdr); // add line numbers and method getLineNumber() LineNumberReader lnRdr = new LineNumberReader(pbRr);... // read data using lnRdr ©SoftMoore ConsultingSlide 24

Related Patterns A decorator is different from an adapter in that a decorator only changes an objects responsibilities, not its interface (but it can add to the interface). A decorator can be viewed as a degenerate composite with only one component. However, a decorator adds additional responsibilities and isn’t intended for object aggregation. A decorator lets you change the “skin” of an object. A strategy lets you change its “guts”. ©SoftMoore ConsultingSlide 25

References Decorator pattern (Wikipedia) Decorate your Java Code by David Geary (JavaWorld) Tutorial: Avoid Excessive Subclassing with the Decorator Design Pattern (Burd and Redlich) ©SoftMoore ConsultingSlide 26