Presentation is loading. Please wait.

Presentation is loading. Please wait.

7. Decorator, Façade Patterns

Similar presentations


Presentation on theme: "7. Decorator, Façade Patterns"— Presentation transcript:

1 7. Decorator, Façade Patterns
SE2811 Software Component Design Dr. Rob Hasker (based on slides by Dr. Mark Hornick) 7. Decorator, Façade Patterns

2 The Decorator Pattern

3 Example: Ice Cream Store
What sort of class would IceCream be? What kind of a method is costInCents? Why?

4 Implementation Doubles would only help a bit…
public class Money { private static float LIMIT = 1e8F; public static void main(String[] args) { float num = LIMIT; for(int i = 0; i < 1000; ++i) num += 1.0; System.out.println(LIMIT + " : " + num); num = 0.0F; num += LIMIT; System.out.println(" " + LIMIT + ": " + num); } // output: 1.0E : 1.0E8 E8: E8 Implementation public abstract class IceCream { String description; public String getDescription() { return description; } public abstract int costInCents(); public class Cone extends IceCream { public Cone() { description = “Cone”; } public int costInCents() { return 124; Doubles would only help a bit… Why use cents and not a double?

5 Implementation Why use cents and not a double?
public abstract class IceCream { String description; public String getDescription() { return description; } public abstract int costInCents(); public class Cone extends IceCream { public Cone() { description = “Cone”; } public int costInCents() { return 124; Why use cents and not a double?

6 Example: Ice Cream Store
What sort of class would IceCream be? What kind of a method is costInCents? Why? Subclasses define their own costInCents() But how to track sprinkles? fudge?

7 Extending functionality
CS-1020 11/15/2018 Extending functionality Store sells many topics: fudge, M&Ms, peanuts Sorry, you’ll have to visit Skylight after class Each topping: additional cost These are college students! How should we design the system? College students will park a meal on an ice cream cone… Dr. Mark L. Hornick

8 Decorator Pattern: Goals
Goal: attach additional functionality to an existing class at runtime Goal: avoid extra subclassing Are there cases where you CANNOT subclass? Yes: if base class declared final Goal: avoid modifying existing class … especially if no access to source or the base class used elsewhere

9 Alternative 1: Create a new class for each combination.
Ice Cream Toppings Cone M&M Dish Fudge WaffleCone Peanuts Caramel What can go wrong? Results in class explosion! What happens when a new topping is added? What happens when the cost of a topping (e.g. fudge) changes? Maintenance nightmare!

10 Alternative 2: Flags for the toppings
IceCream public class IceCream { public double costInCents() { int toppingCost = 0; if (hasFudge()) toppingCost += FUDGE_COST; if (hasCaramel()) toppingCost += CARAMEL_COST; return toppingCost; } -description: String -hasFudge: boolean -hasMnM: boolean +getDescription() +cost() +hasFudge() +hasCaramel() ------ Challenge: doesn’t work well with more complex behavior

11 Alternative 2, continued
public class Cone { public double costInCents() { return super.cost(); } What is this method calculating and returning?

12 So what’s the problem? We want to allow existing classes to be easily adapted to incorporate new behavior without modifying existing code. We want a design that is flexible enough to take on new functionality to meet changing requirements. Solution: Decorator Pattern

13

14

15 Using the Decorator Pattern
Take the IceCream object Let’s create the Cone object. IceCream cone = new Cone(); Decorate it with the Fudge topping. Create a Fudge object and wrap it around Cone. cone = new Fudge(cone); Decorate it with the Nuts topping. Create a Nuts object and wrap it around Cone. cone = new Nuts(cone); Call the cost method and rely on delegation to add the cost of all toppings. Call cost on the outmost decorator. System.out.println(cone.cost());

16 What’s going on here? Open-closed principle: Can extend at will
Classes should be open for extension, but closed to modification Can extend at will No final classes!? Supports new applications of existing code Don’t alter the existing code! It may be used elsewhere! At the least it means new unit tests

17 Evaluation What’s good about the decorator? What’s bad? CS-1020
11/15/2018 Evaluation What’s good about the decorator? What’s bad? Good: can provide new functionality/responsibilities on old classes; Bad: can result in extra classes Dr. Mark L. Hornick

18 Summary Decorators: same super-type as objects being decorated
One or more decorators can be used to wrap an object Can pass decorated object anywhere original can be passed Decorated: adds behavior before or after delegating to the decorated object Can decorate objects at run time … with multiple decorators Supports open-closed principle: open to extension, closed to modification

19 java.io: many classes for I/O
OutputStream, FileOutputStream, PipedOutputStream, DataOutputStream, ObjectOutputStream, PrintStream, PrintWriter, … Associations between these not clear from Java API documentation

20 But note: simply applying Decorator

21 Decorator pattern applied to input streams:
Create custom stream decorators by extending FilterOutputStream and FilterInputStream

22 Demonstration

23 Recall: Adapter (Wrapper) Pattern
Existing System Adapter Implements the interface your classes expect Uses the vendor interface to service your requests. Vendor2 Class Existing System Vendor2 Class Adapter

24 The Adapter configuration
1. The original ServiceProvider class is obsolete and discarded new methods 2. An interface declaring the same methods as the original ServiceProvider is created. 3. A replacement class for the original similar functionality but with a the adaptee

25 The Adapter Pattern features
The client makes a request to the adapter by calling a method on it programming to the interface that mimics the methods of the original class The adapter translates the request into one or more calls on the adaptee The amount of code is usually small, but may be complex due to indirect mappings from the original methods to the new methods The adapter transforms data or results from the adaptee into the form expected by the client The client receives the results of the call and doesn’t care that there is an adapter doing the translation. The only change to the client is that it must create an instance of the adapter rather than the original vendor class.

26 When to use Adapter Legacy code exists that interfaces to a class library that has changed Revision change Vendor change New application is being developed that will have to interface to a class library that has yet to be defined Define an interface and write the adapter later

27 But suppose you want to watch a Movie...
Use multiple interfaces (remotes) to Turn on Receiver/amplifier Turn on TV/Monitor Turn on DVD player Set the Receiver input to DVD Put the Monitor in HDMI input mode Set the Receiver volume to medium Set Receiver to DTS Surround Start the DVD player. Interacting with the following classes: Receiver/Amplifier TV/Monitor DVD

28 To decrease the complexity…
New class: TheaterFacade For instance: a media controller Exposes a few methods such as watchMovie() The façade treats the various components as a sub system and calls on them to implement the watchMovie method. To watch a movie, we just call one method, watchMovie and it communicates with the Monitor, DVD, and Receiver for us The façade still leaves the subsystem accessible to be used directly If you need the advanced functionality of the subsystem classes, they are available for use

29 The Problem Complex system Difficult for clients (blue) to deal with
Multiple subsystems Each with its own interface Each with many methods Difficult for clients (blue) to deal with 29

30 Facade Solution Solution Centralize subsystem interface
Simplify/reduce number of centralized methods Façade presents new unified “face” to clients Facade 30

31 Removing the burden from beginning Java developers with a Façade (WinPlotter)

32 Generic Pattern

33 Facade Consequences Shields clients from subsystem components
Make subsystem easier to use Reduces coupling from client to subsystem classes Allow internal classes to change freely Permit “layering” of system function Level of client-subsystem coupling Make Facade an abstract class Different concrete subclasses for different implementations of the subsystem Configure the façade object with different subsystem objects 33

34 Facade Applications Interface to existing library
Unify or “clean up” complex interface Design layered system Various service levels Façade abstracts interface of each level Provide abstract interfaces To alternative implementations 34

35 Three patterns... Facade Adapter Proxy Provide “clean” interface
Underlying operations still available Adapter Conform interface to a specific client Adapt new set of classes to old Stabilize interface to library under development Proxy Interface to remote client or controlled access to a resource Underlying operations not available 35

36 Review Façade: clean interface to complex subsystems
Decorator: adding properties to objects without using inheritance Composition Over Extension principle


Download ppt "7. Decorator, Façade Patterns"

Similar presentations


Ads by Google