Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright W. Howden1 Singleton, Wrapper, and Facade Patterns CSE 111.

Similar presentations

Presentation on theme: "Copyright W. Howden1 Singleton, Wrapper, and Facade Patterns CSE 111."— Presentation transcript:

1 Copyright W. Howden1 Singleton, Wrapper, and Facade Patterns CSE 111

2 Patterns Pattern Components: Context + problem -> solution Purpose of a pattern describes a problem that occurs over and over and the core of a design idea that can be used over and over without using the same solution twice you must re-implement a pattern in each application Copyright W. Howden2

3 History 1991: Patterns Workshop at OOPSOL conference 1994: Design Patterns: Elements of Reusable Object-Oriented Software, by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides (the GOF – Gang of Four) Copyright W. Howden3

4 Design Patterns (GOF) Creational Abstract Factory, Singleton, Factory Method, Builder, Prototype Structural Adapter, Bridge, Composite, Decorator, Façade, Flyweight, Proxy Behavioral Chain of Responsibility, Command(undo/redo), Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template, Method, Visitor Non-GoF patterns Model-View-Controller, Expert, Creator, Controller Copyright W. Howden4

5 5 Singleton Pattern Satisfies the following requirements: –global access to data –only one copy/instance of a class –lazy instantiation the one copy is not created until it is needed desired because of potential costly initialization, and object may not always be needed Applications –logging object, wherein different parts of the system are recording log events

6 How is it done? public class Logger {private static Logger instance; // additional class variables private Logger() {} public static Logger getInstance() {if (instance == null) {instance = new Logger();} return instance; } // possible additional methods } Copyright W. Howden6

7 Interesting Properties private constructor ensures that no one can directly create instances of the class have to go through getInstance() which only allows one instance getInstance() method is static since we can’t create an instance of the class, how are we going to call the getInstance method? –make it static Lazy instantiation: not created until needed Copyright W. Howden7

8 Eager Instantiation Version public class Logger {private static Logger instance = new Logger(); // additional class variables private Logger() {} public static Logger getInstance() {return instance; } // possible additional methods } Copyright W. Howden8

9 How does Eager Work When an instance of a class is created, or its static variables are referenced, the class loader loads Logger At this point all of its static initializers are run, so that the singleton instance of Logger Copyright W. Howden9

10 All Static Alteranative public class Logger {// public static class variables private Logger() {} // public static methods } Copyright W. Howden10

11 Singletons vs Static? Singletons can implement lazy evaluation Singletons can be modified to form “multitons” (up to k instances, where k > 1) Singletons are objects and can be passed around Singletons can implement interfaces –(e.g. the non-static methods) Copyright W. Howden11

12 Copyright W. Howden12 DS Singleton Example Want to have a globally accessible object that records session history statistics Gets updated from different places, e.g. when different kinds of messages are generated Use the singleton pattern for a History class

13 Copyright W. Howden13 Wrappers Take an existing entity and alter its behavior or interface by “embedding” it inside a class Types of wrappers –> Decorator: alters behavior or responsibilities but not the interface –Adapter: emphasis is on altering interface, but could add some additional responsibilities or behavior

14 Copyright W. Howden14 Decorator Strategies? Wrapper class subclasses wrappee class so has same interface Wrapper constructor takes wrappee as an argument, so it is “altering” it at runtime –uses wrappee methods to define new behavior –alters behavior without subclassing –client calls wrapper methods

15 Copyright W. Howden15 Composition Strategy for Decorators Wrappee +Wrapper(in Wrappee x) -Wrappee:x Wrapper

16 Comments An object may be multiply-wrapped, requiring a more complex pattern Set of possible behavior decorations can be chosen at run time Will see this in the following DS example Copyright W. Howden16

17 Dating System Example for Decorator Wrapper We decide to allow the user to ask to get a date, as before, but also specify several possible additional options 1.send an email to the selected date 2.send a reminder email to me 3.send flowers to the selected date One or none of these “decorations” can be added Copyright W. Howden17

18 DS Decorator Pattern Class Structure Copyright W. Howden18

19 Class Usage Pattern Copyright W. Howden19

20 Sequence of Execute Calls Message 5 will call the execute() method of the “outermost” class. This could be dR:DateRequest if there were no decorator options specified. Suppose there was one, the EmailDate option. Then the outermost execute() method will be that of the instance x of EmailDate that was created. x.execute() will call the execute() method for dR:DateRequst, which was passed in by the constructor for x. dr.execute() will find a date, i.e. memberData for that date, and return it to the calling x.execute(). x,execute() will “decorate” the return by sending an email It will then return the date to the calling DomainLogic method. Copyright W. Howden20

21 Notes on Class Structure No concrete decorator class is used more than once The DateRequest class is used exactly once Copyright W. Howden21

22 execute() definitions DR: calls its component’s execute() DRDecorator: abstract DateRequest: original method that looks for a date, returns null if no date found. Other wise returns an instance of MemberData Concrete wrappers: execute() calls its component’s execute() Copyright W. Howden22

23 Concrete Decorator execute() Definitions – E.g. EmailMe class EmailMe extends DRDecorator { DR: mydR public EmailMe(DR dR) { this.mydR = dR);} public MemberData execute() {memberData = mydR.execute(); if (memberData != null) {/** send email to me;} return(memberData); } Copyright W. Howden23

24 Possible Additional Details Might create a new class called Date –Consists of both the MemberData for the user/dater asking for a data, and the MemberData for the discovered datee –Returned from the execute() method of a new DateRequest when a date is found Why? –when the EmailMe decorator has to email me, the user, it would have the data necessary to send that email Copyright W. Howden24

25 Copyright W. Howden25 An Additional Decorator Example – Java Stream Wrapper FileInputStream has a simple read() operation that reads a single byte Very inefficient, would like to buffer the input Solution: “decorate” FileInputStream with a decorator class BufferedInputStream Diagram shows two wrappers for FileInput Stream –BufferedInputStream and LineNumberInputStream

26 File Decoration in Java Copyright W. Howden26

27 Comments on File Decorator BufferedInputStream and LineNumberInputStream both have class variables of type InputStream because they subclass the abstract decorator class FilterInputStream Instances of wrappers can be created with instances of FileInputStream and certain other streams such as StringBufferInputStream Copyright W. Howden27

28 Copyright W. Howden28 Wrappers (once again) Take an existing entity and alter its behavior or interface by “embedding” it inside a class Types of wrappers –Decorator: alters behavior or responsibilities but not the interface –> Adapter: emphasis is on altering interface, but could add some additional responsibilities or behavior

29 Copyright W. Howden29 Adapter Strategies Can use either inheritance or composition –Inheritance, or Class Adapter Adapter class implements the required new interface Adapter extends the adaptee, with new methods for performing the adaptee responsibilities, which conform to the new interface –Composition, or Object Adapter Adapter class implements the required new interface Adapter’s constructor takes an adaptee object as an argument Adaptor methods reference the adaptee object via its adaptee class methods

30 Copyright W. Howden30 Class Adapter

31 Copyright W. Howden31 Object Adapter

32 DS Adapter Pattern - Object Adapter Original DateRequest has a constructor with two parameters: userName and daterPrefs It returns a memberData object (or null) In the expanded version given in our Decorator pattern, two of the decorators need the email address for the userMember in the case where a date is found -> use a DateRequest adaptor to return a Date object Copyright W. Howden32

33 DateRequestAdapter Copyright W. Howden33

34 New Adapter execute() Needs to augment the returned MemberData object to form a Date object Uses the getMemberData(UserName) method in the DataBase subsystem’s interface to get the needed memberData Returns null if MemberData return is null or if UserName name is not in the DB Copyright W. Howden34

35 Risky Programming? The first version of the system returned a MemberData object for a member who satisfied the DaterPrefs The UserName it passed was actually ignored, so does this mean a date could be found for a person who was not a member? No, since UserName is the type of a name that has been verified to be a user Copyright W. Howden35

36 Another Object Adapter Need to create a class version of the Boolean primitive data type used to pass data back out through a method parameter recall all parameters in Java are call by value –primitive value of address of object Target interface for new adapter class has set() and get() methods instead of the infix methods for primitive types (i.e. x = y) Copyright W. Howden36

37 Object Adaptor Copyright W. Howden37

38 Copyright W. Howden38 Interface: BoolRefInterface { setBool(boolean b); boolean getBool() } Adaptee: primitive boolean value Adaptor: class BooleanRef implements BoolRefInterface {public boolean b; public BooleanRef(boolean x){this.b = x} public set(boolean x) {this.b = b;} public get() {return this.b;} }

39 Copyright W. Howden39 Facade Pattern Purpose: Provide a unified interface to a set of classes in a subsystem. Rationale: Makes system easier to use, promotes low coupling, supports layering, re-use DS Example: the Business/Domain Logic and the DataBase subsystems have facade classes that serve as subsystem controllers and interfaces

40 Without and With a Facade Copyright W. Howden40

41 Comments on Phase II Deliverables Re-doing design documents with added functionality (domain models, sequence diagrams, collaboration diagrams, class diagrams) New models: State model for GUI Observations on each of the patterns where used if used where may or may not be useful Copyright W. Howden41

42 Assignment 12 Consider potential applications of the the three patterns here: –singleton, wrappers, facade –either apply them in your project or explain why you do not think it is practical or useful, with examples Copyright W. Howden42

Download ppt "Copyright W. Howden1 Singleton, Wrapper, and Facade Patterns CSE 111."

Similar presentations

Ads by Google