Decorator Explained. Intent Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub-classing for.

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.
CS 210 Introduction to Design Patterns September 12 th, 2006.
The Bridge Pattern.. Intent Decouple an abstraction from its implementation so that the two can vary independently Also known as: Handle/Body.
Oct Ron McFadyen1 Collaborations Collaboration : an arrangement of classes, links, roles in a context to implement some behaviour. Name of.
Marcelo Santos 1 Design Patterns Object Oriented Programming Advanced Course 2007.
Marcelo Santos – OOAD-CDT309, Spring 2008, IDE-MdH 1 Object-Oriented Analysis and Design - CDT309 Period 4, Spring 2008 More design patterns.
March Ron McFadyen1 Design Patterns In software engineering, a design pattern is a generally repeatable solution to a commonly-occurring problem.
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.
Winter 2011ACS-3913 Ron McFadyen1 Decorator Sometimes we need a way to add responsibilities to an object dynamically and transparently. The Decorator pattern.
Design Patterns.
Department of Computer Science, York University Object Oriented Software Construction 16/09/ :52 PM 0 COSC3311 – Software Design Decorator Pattern.
Structural Pattern: Decorator There are times when the use of subclasses to modify the behavior of individual objects is problematic. C h a p t e r 4.
9/28/01F-1 © 2001 T. Horton CS 494 Object-Oriented Analysis & Design Design Patterns.
Lecture 16 Composition vs Inheritance: The Final Chapter.
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).
Jan Ron McFadyen1 Decorator Sometimes we need a way to add responsibilities to an object dynamically and transparently. The Decorator pattern.
Decorator Pattern So many options!. Starbuzz Coffee  Want to offer a variety of combinations of coffee and condiments  Cost of a cup depends on the.
1 Computer Science 340 Software Design & Testing Inheritance.
Decorator Design Pattern Rick Mercer CSC 335: Object-Oriented Programming and Design.
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.
Factory Method Explained. Intent  Define an interface for creating an object, but let subclasses decide which class to instantiate.  Factory Method.
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University The Strategy Pattern.
CPS Inheritance and the Yahtzee program l In version of Yahtzee given previously, scorecard.h held information about every score-card entry, e.g.,
1 Advanced Object-oriented Design – Principles and Patterns Structural Design Patterns.
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.
Decorator Design Pattern Rick Mercer CSC 335: Object-Oriented Programming and Design.
S.Ducasse Stéphane Ducasse 1 Decorator.
The Decorator Pattern (Structural) ©SoftMoore ConsultingSlide 1.
Decorator Design Pattern Phillip Shin. Overview Problem Solution Example Key points.
F-1 © 2007 T. Horton CS 4240 Principles of SW Design More design principles LSP, OCP, DIP, … And another pattern Decorator.
Banaras Hindu University. A Course on Software Reuse by Design Patterns and Frameworks.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
S.Ducasse Stéphane Ducasse 1 Adapter.
CS 350 – Software Design The Decorator Pattern – Chapter 17 In this chapter we expand our e-commerce case study and learn how to use the Decorator Pattern.
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.
Builder Introduction. Intent Separate the construction of a complex object from its representation so that the same construction process can create different.
CS 210 Introduction to Design Patterns September 14 th, 2006.
Design Patterns: MORE Examples
Object-Orientated Analysis, Design and Programming
Abstract Factory Pattern
Linzhang Wang Dept. of Computer Sci&Tech, Nanjing University
Factory Patterns 1.
Behavioral Design Patterns
Abstract Factory Pattern
Intent (Thanks to Jim Fawcett for the slides)
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
OO Design Patterns - Decorator
Decorator Pattern Richard Gesick.
Structural Patterns: Adapter and Bridge
7. Decorator SE2811 Software Component Design
Decorator.
Decorator Pattern.
Software Design Lecture 10.
Presentation transcript:

Decorator Explained

Intent Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub-classing for extending functionality Also Known As – Wrapper 2

Motivation Sometimes we want to add responsibilities to individual objects. A graphical user interface toolkit, for example,should let you add properties like borders or behaviors like scrolling to any user interface component One way to add responsibilities is with inheritance. Inheriting a border from another class puts a border around every subclass instance. This is inflexible, however, because the choice of border is made statically. A client can't control how and when to decorate the component with a border. 3

Motivation A more flexible approach is to enclose the component in another object that adds the border The enclosing object is called a decorator The decorator conforms to the interface of the component it decorates so that its presence is transparent to the component's clients. The decorator forwards requests to the component and may perform additional actions (such as drawing a border) before or after forwarding. 4

Motivation Transparency lets you nest decorators recursively, thereby allowing an unlimited number of added responsibilities 5

Motivation Suppose we have a TextView object that displays text in a window. TextView has no scroll bars by default, because we might not always need them When we do, we can use a ScrollDecorator to add them Suppose we also want to add a thick black border around the TextView. We can use a BorderDecorator to add this as well We simply compose the decorators with the TextView to produce the desired results. 6

Motivation The following object diagram shows how to compose a TextView object with BorderDecorator and ScrollDecorator objects to produce a bordered, scrollable text view 7

Motivation The ScrollDecorator and BorderDecorator classes are subclasses or concrete classes of Decorator Decorator is an abstract class for visual components that decorate other visual components 8

Motivation 9

VisualComponent is the abstract class for visual objects. It defines their drawing and event handling interface. Decorator class simply forwards draw requests to its component, and Decorator subclasses can extend this operation. Decorator subclasses are free to add operations for specific functionality For example, ScrollDecorator's ScrollTo operation lets other objects scroll the interface if they know there happens to be a ScrollDecorator object in the interface. 10

Motivation The important aspect of this pattern is that it lets decorators appear anywhere a VisualComponent can That way clients generally can't tell the difference between a decorated component and an undecorated one, and so they don't depend at all on the decoration 11

Applicability Use Decorator – To add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects. – For responsibilities that can be withdrawn. – When extension by sub-classing is impractical. Sometimes a large number of independent extensions are possible and would produce an explosion of subclasses to support every combination. Or a class definition may be hidden or otherwise unavailable for sub-classing 12

Structure 13

Participants Component (VisualComponent) – defines the interface for objects that can have responsibilities added to them dynamically. ConcreteComponent (TextView) – 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 (BorderDecorator, ScrollDecorator) – adds responsibilities to the component. 14

Collaborations Decorator forwards requests to its Component object. It may optionally perform additional operations before and after forwarding the request. 15

Consequences More flexibility than static inheritance – With decorators, responsibilities can be added and removed at run-time simply by attaching and detaching them. In contrast, inheritance requires creating a new class for each additional responsibility (e.g., BorderedScrollableTextView, BorderedTextView). This gives rise to many classes and increases the complexity of a system. Avoids feature-laden classes high up in the hierarchy – Decorator offers a pay-as-you-go approach to adding responsibilities. Instead of trying to support all foreseeable features in a complex, customizable class, you can define a simple class and add functionality incrementally with Decorator objects. Functionality can be composed from simple pieces. As a result, an application needn't pay for features it doesn't use. It's also easy to define new kinds of Decorators independently from the classes of objects they extend, even for unforeseen extensions 16

Consequences A decorator and its component aren't identical – A decorator acts as a transparent enclosure. But from an object identity point of view, a decorated component is not identical to the component itself Lots of little objects – A design that uses Decorator often results in systems composed of lots of little objects that all look alike. Although these systems are easy to customize by those who understand them, they can be hard to learn and debug 17

Implementation Issues Interface conformance - A decorator object's interface must conform to the interface of the component it decorates. ConcreteDecorator classes must therefore inherit from a common class. Omitting the abstract Decorator class - There's no need to define an abstract Decorator class when you only need to add one responsibility. In that case, you can merge Decorator's responsibility for forwarding requests to the component into the ConcreteDecorator 18

Starbuzz Coffee 19

Open-Closed Design Principle Classes should be open for extension, but closed for modification Our goal is to allow classes to be easily extended to incorporate new behavior without modifying existing code. We can get designs that are resilient to change and flexible enough to take on new functionality to meet changing requirements Let’s apply decorator pattern on starbuzz case. 20

Applying Decorator to Starbuzz Okay, we’ve seen that representing our beverage plus condiment pricing scheme with inheritance has not worked out very well – we get class explosions, rigid designs, or we add functionality to the base class that isn’t appropriate for some of the subclasses So, here’s what we’ll do instead: we’ll start with a beverage and decorate it with the condiments at runtime. For example, if the customer wants a Dark Roast with Mocha and Whip then, 21

Applying Decorator to Starbuzz We will perform the following steps 1.Take a DarkRoast object 2.Decorate it with a Mocha object 3.Decorate it with a Whip object 4.Call the cost() method and rely on delegation to add on the condiment costs 22

Applying Decorator to Starbuzz 23 Remember that DarkRoast inherits from Beverage and has a cost() method that computes the cost of the drink So, Mocha has a cost() method too, and through polymorphism we can treat any Beverage wrapped in Mocha as a Beverage, too (because Mocha is a subtype of Beverage) So, a DarkRoast wrapped in Mocha and Whip is still a Beverage and we can do anything with it we can do with a DarkRoast, including call its cost() method.

Calculating Cost of Starbuzz Coffee Now it’s time to compute the cost for the customer. We do this by calling cost() on the outermost decorator, Whip, and Whip is going to delegate computing the cost to the objects it decorates. Once it gets a cost, it will add on the cost of the Whip. 24

Class Structure for Starbuzz 25

Some Important Facts So here we’re using inheritance to achieve the type matching, but we aren’t using inheritance to get behavior When we compose a decorator with a component, we are adding new behavior. We are acquiring new behavior not by inheriting it from a superclass, but by composing objects together. 26

Code for Starbuzz… Let’s define the abstract class Beverage public abstract class Beverage { protected String m_description; // get a description of the beverage public virtual String Description { get { return m_description; } } // calculate cost of the beverage public abstract double Cost(); } 27

Concrete Beverage Classes // HouseBlend coffee implements Beverage public class HouseBlend : Beverage { // Constructor public HouseBlend() { m_description = "House Blend"; } // calculate base cost of House Blend public override double Cost() { return 0.89; } } // DarkRoast coffee implements Beverage public class DarkRoast : Beverage { // Constructor public DarkRoast() { m_description = "Dark Roast"; } // calculate base cost of Dark Roast public override double Cost() { return 1.00; } } 28

Decorators (Condiments) // abstract base class CondimentDecorator is-a Beverage public abstract class CondimentDecorator : Beverage {} public class Mocha : CondimentDecorator { private Beverage m_beverage; public Mocha(Beverage beverage) { this.m_beverage = beverage; } // getter implements abstract class Description public override String Description{ get{return m_beverage.Description + ", Mocha“; } } // get the Cost of the condiment plus the base-cost of the original beverage public override double Cost() { return m_beverage.Cost(); } 29

Decorators (Condiments) public class Milk : CondimentDecorator { private Beverage m_beverage; public Milk(Beverage beverage) { this.m_beverage = beverage; } // getter implements abstract class public override String Description{ Get{return m_beverage.Description + ", Milk"; } // get the Cost of the condiment plus the base- //cost of the original beverage public override double Cost() { return m_beverage.Cost(); } public class Whip : CondimentDecorator { private Beverage m_beverage; public Whip(Beverage beverage) { this.m_beverage = beverage; } // getter implements abstract class Description public override String Description { get{return m_beverage.Description + ", Whip"; } // get the Cost of the condiment plus the base-// cost of the original beverage public override double Cost() { return m_beverage.Cost(); } 30

Calling Program class Program{ static void Main(string[] args) { //Ordering an Espresso Beverage beverage = new Espresso(); Console.WriteLine("Your Order is: " + beverage.Description + " & would Cost: " + beverage.Cost()); Console.ReadLine(); //Ordering a Darkroast with Double Mocha and Whip Beverage beveragetwo = new DarkRoast(); beveragetwo = new Mocha(beveragetwo); beveragetwo = new Whip(beveragetwo); Console.WriteLine("Your Order is: " + beveragetwo.Description + " & would Cost: " + beveragetwo.Cost()); Console.ReadLine(); //Ordering a Houseblend with Soye Mocha and Whip Beverage beveragethree = new HouseBlend(); beveragethree = new Soye(beveragethree); beveragethree = new Mocha(beveragethree); beveragethree = new Whip(beveragethree); Console.WriteLine("Your Order is: " + beveragethree.Description + " & would Cost: " + beveragethree.Cost()); Console.ReadLine(); } 31

Outputs 32

Quiz # 2 Looking at the Diagram, please answer the two questions. 1.What’s wrong with the design. How can we make this design more flexible? 2.Please make a diagram of the changed design after applying the appropriate design principle? 33 Pizza Store NyStyle Cheeze Pizza NyStyle Cheeze Pizza NyStyle Cheeze Pizza NyStyle Cheese Pizza Chicago Cheeze Pizza Chicago Cheeze Pizza Chicago Cheeze Pizza Chicago Cheese Pizza