Вы находитесь на странице: 1из 42

Singleton, Wrapper,

and Facade Patterns


CSE 111

Copyright W. Howden 1
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, Faade, 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
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

Copyright W. Howden 5
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 cant 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. 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
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 12
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 13
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 14
Composition Strategy for
Decorators

Wrappee

Wrapper
-Wrappee:x
+Wrapper(in Wrappee x)

Copyright W. Howden 15
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 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. Howden 17
DS Decorator Pattern
Class Structure

Copyright W. Howden 18
Class Usage Pattern

Copyright W. Howden 19
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 components 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
components 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
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

Copyright W. Howden 25
File Decoration in Java

Copyright W. Howden 26
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
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 28
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
Adapters constructor takes an adaptee object as an argument
Adaptor methods reference the adaptee object via its adaptee
class methods

Copyright W. Howden 29
Class Adapter
Client interface
Target
+request'()

Adaptor Adaptee

+request'() +request()

Copyright W. Howden 30
Object Adapter
Client interface
Target
+request'()

Adaptor
Adaptee: adaptee
-Adaptee: adaptee
+Adaptor(in adaptee) +request()
+request'()

Copyright W. Howden 31
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
DateRequestAdapter

Copyright W. Howden 33
New Adapter execute()
Needs to augment the returned
MemberData object to form a Date object
Uses the getMemberData(UserName)
method in the DataBase subsystems
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
Object Adaptor

Copyright W. Howden 37
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;}
}

Copyright W. Howden 38
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

Copyright W. Howden 39
Without and With a Facade

Facade

System System

Copyright W. Howden 40
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
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. Howden 42

Вам также может понравиться