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 Access Modifiers (bullets)
SE-2811 4/5/2019 Access Modifiers (bullets) Code to most restrictive level of access modification that is possible in a given context: Use public for constants and methods; never for attributes. On methods: only on those you want to support for public consumption Use protected to allow derived classes in any package access to members Use /*package*/ if cooperating classes in the same package need access to attributes or special methods Use private to completely guard members from view outside the defining class Dr. Josiah Yoder

3 Access Modifiers (table)
SE-2811 4/5/2019 Access Modifiers (table) Access Levels Modifier Class Package Subclass World public Y protected N /*package*/ private Adapted from Oracle’s Java tutorial sscontrol.html SE-2811 Dr. Mark L. Hornick Dr. Josiah Yoder

4 The Decorator Pattern

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

6 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?

7 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?

8 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?

9 Extending functionality
CS-1020 4/5/2019 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

10 IceCream Inheritance Model Design Review
SE-2811 4/5/2019 IceCream Inheritance Model Design Review Any potential changes? Keep current design? Example from Head First Design Patterns SE-2811 Dr. Mark L. Hornick Dr. Yoder

11 SE-2811 4/5/2019 Time for Ice Cream 2.0 Want to be able to add Sprinkles, Fudge, M&Ms, etc. to our ice cream Exercise: With your neighbors, create a design to include these “decorators” and have the cost function return their cost Draw a UML class diagram for your system Write short snippets of pseudocode if helpful Please use multiple classes to keep each class small (cohesive) This isn’t necessarily needed for THIS problem, but helps with larger-scale problems Example from Head First Design Patterns SE-2811 Dr. Mark L. Hornick Dr. Yoder

12 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

13 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!

14 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

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

16 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

17

18

19 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());

20 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

21 Evaluation What’s good about the decorator? What’s bad? CS-1020
4/5/2019 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

22 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

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

24 But note: simply applying Decorator

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

26 Byte Input Streams SE-2811 Dr. Mark L. Hornick

27 Demonstration

28 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

29 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

30 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.

31 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

32 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

33 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

34 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 34

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

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

37 Generic Pattern

38 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 38

39 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 39

40 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 40

41 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