copyright w. howden1 singleton, wrapper, and facade patterns cse 111
TRANSCRIPT
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. Howden 2
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. Howden 3
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. Howden 4
Copyright W. Howden 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
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. Howden 6
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 neededCopyright W. Howden 7
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. Howden 8
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. Howden 9
All Static Alteranative
public class Logger
{ // public static class variables
private Logger() {}
// public static methods
}
Copyright W. Howden 10
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. Howden 11
Copyright W. Howden 12
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
Copyright W. Howden 13
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
Copyright W. Howden 14
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
Copyright W. Howden 15
Composition Strategy for Decorators
Wrappee
+Wrapper(in Wrappee x)-Wrappee:x
Wrapper
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. Howden 16
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 options1. 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. Howden 17
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. Howden 20
Notes on Class Structure
• No concrete decorator class is used more than once
• The DateRequest class is used exactly once
Copyright W. Howden 21
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. Howden 22
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. Howden 23
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. Howden 24
Copyright W. Howden 25
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
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. Howden 27
Copyright W. Howden 28
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
Copyright W. Howden 29
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
Copyright W. Howden 30
Class Adapter
Client
+request'()
«interface»Target
+request'()
Adaptor
+request()
Adaptee
Copyright W. Howden 31
Object Adapter
+Adaptor(in adaptee)+request'()
-Adaptee: adapteeAdaptor
+request()
Adaptee: adaptee
Client
+request'()
«interface»Target
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. Howden 32
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. Howden 34
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. Howden 35
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. Howden 36
Copyright W. Howden 38
Interface:BoolRefInterface { setBool(boolean b); boolean getBool() }
Adaptee: primitive boolean valueAdaptor:
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;}
}
Copyright W. Howden 39
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
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. Howden 41