410 likes | 422 Views
Learn about the Decorator Pattern and how it can be applied to an Ice Cream Store to add toppings to ice cream flavors dynamically at runtime. Explore the benefits and drawbacks of different approaches.
E N D
SE2811 Software Component Design Dr. Rob Hasker (based on slides by Dr. Mark Hornick) 7. Decorator, Façade Patterns
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
Access Modifiers (table) • Adapted from Oracle’s Java tutorial http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html SE-2811 Dr. Mark L. Hornick
Example: Ice Cream Store • What sort of class would IceCream be? • What kind of a method is costInCents? Why?
public class Money { private static float LIMIT = 1e8F; public static void main(String[] args) { float num = LIMIT; for(inti = 0; i < 1000; ++i) num += 1.0; System.out.println(LIMIT + " + 1000: " + num); num = 0.0F; for(inti = 0; i < 1000; ++i) num += 1.0; num += LIMIT; System.out.println("1000 + " + LIMIT + ": " + num); } } // output: 1.0E8 + 1000: 1.0E8 1000 + 1.0E8: 1.00001E8 Implementation public abstract class IceCream { String description; public String getDescription() { return description; } public abstract intcostInCents(); } public class Cone extends IceCream { public Cone() { description = “Cone”; } public intcostInCents() { return 124; } } Doubles would only help a bit… Why use cents and not a double?
Implementation public abstract class IceCream { String description; public String getDescription() { return description; } public abstract intcostInCents(); } public class Cone extends IceCream { public Cone() { description = “Cone”; } public intcostInCents() { return 124; } } Why use cents and not a double?
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?
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?
IceCream Inheritance ModelDesign Review • Any potential changes? • Keep current design? SE-2811 Dr. Mark L. Hornick
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 SE-2811 Dr. Mark L. Hornick
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
Alternative 1: Create a new class for each combination. 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!
Alternative 2: Flags for the toppings IceCream public class IceCream { … public double costInCents() { inttoppingCost = 0; if (hasFudge()) toppingCost += FUDGE_COST; if (hasCaramel()) toppingCost += CARAMEL_COST; … return toppingCost; } } -description: String -hasFudge: boolean -hasMnM: boolean ------- +getDescription() +cost() +hasFudge() +hasCaramel() ------
Alternative 2, continued public class Cone { … public double costInCents() { return 124 + super.cost(); } } What is this method calculating and returning?
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
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());
What’s going on here? • Open-closed principle: • 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
Evaluation • What’s good about the decorator? • What’s bad?
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
java.io: many classes for I/O OutputStream, FileOutputStream, PipedOutputStream, DataOutputStream, ObjectOutputStream, PrintStream, PrintWriter, … Associations between these not clear from Java API documentation
Decorator pattern applied to input streams: Create custom stream decorators by extending FilterOutputStream and FilterInputStream
Byte Input Streams SE-2811 Dr. Mark L. Hornick
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
The Adapter configuration 1. The original ServiceProvider class is obsolete and discarded 4. An adapter class is written which maps calls from the original methods to the new methods 2. An interface declaring the same methods as the original ServiceProvider is created. 3. A replacement class for the original ServiceProvider is found that provides similar functionality but with a Different set of methods: the adaptee
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.
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
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
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
The Problem • Complex system • Multiple subsystems • Each with its own interface • Each with many methods • Difficult for clients (blue) to deal with
Facade Solution • Solution • Centralize subsystem interface • Simplify/reduce number of centralized methods • Façade presents new unified “face” to clients Facade
Removing the burden from beginning Java developers with a Façade (WinPlotter)
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
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
Three patterns... • Facade • 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
Review • Façade: clean interface to complex subsystems • Decorator: adding properties to objects without using inheritance • Composition Over Extension principle