Design Patterns
Download
Report
Transcript Design Patterns
CS 494
Object-Oriented Analysis & Design
Design Patterns
© 2001 T. Horton
9/28/01
F-1
Readings
• Chapter 1 of GoF book
– Especially pp. 1-10, 24-26
– I’ll get this to you (toolkit, reserve, Web?)
• Eckel’s Thinking in Patterns, on Web
– Chap. 1, “The pattern concept”
– Chap. 5, “Factories”
• Handouts on various patterns
9/28/01
F-2
Idioms, Patterns, Frameworks
• Idiom: a small language-specific pattern or technique
– A more primitive building block
• Design pattern: a description of a problem that
reoccurs and an outline of an approach to solving that
problem
– Generally domain, language independent
– Also, analysis patterns
• Framework:
– A partially completed design that can be extended to
solve a problem in a domain
• Horizontal vs. vertical
9/28/01
F-3
Examples of C++ Idioms
• Use of an Init() function in constructors
– If there are many constructors, make each one call a
private function Init()
• Init() guarantees all possible attributes are initialized
• Initialization code in one place despite multiple
constructors
• Don’t do real work in a constructor
– Define an Open() member function
• Constructors just do initialization
• Open() called immediately after construction
– Constructors can’t return errors
• They can throw exceptions
9/28/01
F-4
Design Patterns: Essential Elements
• Pattern name
– A vocabulary of patterns is beneficial
• Problem
– When to apply the pattern, what context.
– How to represent, organize components
– Conditions to be met before using
• Solution
– Design elements: relationships, responsibilities,
collaborations
– A template for a solution that you implement
• Consequences
– Results and trade-offs that result from using the pattern
– Needed to evaluate design alternatives
9/28/01
F-5
Patterns Are (and Aren’t)
• Name and description of a proven solution to
a problem
• Documentation of a design decision
• They’re not:
– Reusable code, class libraries, etc. (At a higher
level)
– Do not require complex implementations
– Always the best solution to a given situation
– Simply “a good thing to do”
9/28/01
F-6
Describing Design Patterns
• The GoF defined a standard format
– Generally followed
– Not just a UML diagram!
• Pattern Format (13 sections):
–
–
–
–
Pattern name and classification
Intent: what’s it do? Rationale?
Also known as
Motivation
• A scenario that illustrates a sample problem and how
this patterns helps solve it.
– Applicability
• For which situations can this be applied?
– Structure
• Graphical representation (e.g. UML)
9/28/01
F-7
Pattern Format (cont’d)
– Participants
• Classes and objects, their responsibilities
– Collaborations
• How participants interact
– Consequences
– Implementation
• Pitfalls, hints, techniques, language issues
– Sample code
• Code fragments that illustrate the pattern
– Known uses
• From real systems
– Related patterns
• Similar patterns, collaborating patterns
9/28/01
F-8
Example 1: Singleton Pattern
• Context: Only one instance of a class is created.
Everything in the system that needs this class
interacts with that one object.
• Controlling access: Make this instance accessible to
all clients
• Solution:
– The class has a static variable called theInstance (etc)
– The constructor is made private (or protected)
– Clients call a public operation getInstance() that returns
the one instance
• This may construct the instance the very first time or
be given an initializer
9/28/01
F-9
Singleton: Java implementation
public class MySingleton {
private static MySingleton theInstance =
new MySingleton();
private MySingleton() { // constructor
…
}
public static MySingleton getInstance() {
return theInstance;
}
}
9/28/01
F-10
Static Factory Methods
• Singleton patterns uses a static factory method
– Factory: something that creates an instance
• Advantages over a public constructor
– They have names. Example:
BigInteger(int, int, random) vs.
BigInteger.probablePrime()
– Might need more than one constructor with same/similar
signatures
– Can return objects of a subtype (if needed)
• Wrapper class example:
Double d1 = Double .valueOf(“3.14”);
Double d2 = new Double (“3.14”);
• More info: Bloch’s Effective Java
9/28/01
F-11
The State Design Pattern
•
A connection can be in various states
– Handles requests differently depending on state
•
Connection delegates requests to its state object
– Which changes dynamically
9/28/01
F-12
9/28/01
F-13
Categories of Design Patterns
• GoF categories
– Creational
– Structural
– Behavioral
• Can you classify patterns we’ve seen so far?
9/28/01
F-14
Factories for Creating Objects
• Recall ideas about reducing coupling between a client
and objects in an inheritance hierarchy
• Common approaches for achieving this
– Factory pattern (AKA Factory Method pattern)
• A client calls a method to get a reference to an object,
• but only knows its interface or supertype
– Abstract factory:
• A client gets an instance of a factory class
• factory object creates one particular kind of many
related objects
• AKA kit or toolkit pattern
9/28/01
F-15
Factory Method Pattern
• A factory method
– Is called to create an object for the client
– Returns a type that is interface or abstract
class
– May be implemented in several places or in one
Factory class
– Seeks to improve coupling, reduce
dependancies
• Examples in Java (or are they? you decide)
– toString()
– Arrays.asList(obj[] ary) // returns List
– iterator()
9/28/01
F-16
Desired Framework:
But how can Application
create instances of
Document objects without
subclass coupling?
It can’t according to this
diagram. But see next slide!
(From Grand’s book.)
9/28/01
F-17
Solution: Use Document Factory class to
create various types of documents
(From Grand’s book.)
9/28/01
F-18
Factory Method Pattern: General Structure
discriminator is
some parameter that
indicates what kind
of Product subclass
to instantiate
(perhaps a string).
(From Grand’s
book.)
9/28/01
F-19
Another Example: Java Iterator
• What kind of type is Iterator?
– Answer: interface
• How do we get an Iterator object?
– Answer: from a factory method defined in the
collection class
• Consider:
List l1 = Arrays.asList(ary);
Iterator i1 = l1.iterator();
9/28/01
F-20
Abstract Factory Pattern
• Abstract Factory is a class
– That contains a set of related factory methods for
creating various types of objects (e.g. widgets)
– Abstract class: all these are abstract methods
– Developer writes subclass of the Abstract Factory
• Set of methods create related types of objects
– Client instantiates one of several subclasses to get a
particular kind of factory object
• Calls methods on that object to get instances of
different widgets
• Factory creates only widgets of one “family”
9/28/01
F-21
General Overview of Abstract Factory
Note use of static method
in factory class to return
particular concrete
factory object.
This could be a factory
method that takes a string
as a discriminator.
(From Grand’s book.)
9/28/01
F-22
Example of Abstract Factory
(From Grand’s book.)
9/28/01
F-23
Benefit of Abstract Factories: substituting
one factory for another.
Application can be
modified by swapping
out the type of factory it
uses.
(From Martin’s ASD
book.)
9/28/01
F-24
The problem (again): If SomeApp only uses the
Shape interface, it shouldn’t use new to create
instances of concrete classes.
•(From Martin’s ASD book.)
9/28/01
F-25
Abstract Factory is a better Solution: SomeApp uses
a particular ShapeFactory implementation (no use of
new)
Note here that “abstract”
factory is an interface. That
seems fine, but it’s not clear
from this diagram how
SomeApp creates instance
of a concrete factory.
(From Martin’s ASD book.)
9/28/01
F-26
OO Principle: Open-Closed Principle
• The Open-Closed Principle (OCP)
– Classes should be open for extension, but
closed for modification.
• Don’t allow clients to alter your code.
• Allow clients to easily add things to your
classes.
– Provide means of extension
• Example of this: the Observer design pattern
• Note there’s a cost to making classes
extendable
9/28/01
F-27
Another Design Solution for This
• You’re doing Beverages for a coffee shop
• Four types of coffee-drink:
– HouseBlend, DarkRoast, Decaf, Espresso
• Also can add (for a cost):
– SteamedMilk, Soy, Mocha, WhippedMilk
• Want a cost() method in each class to calculate costs
• Question: how to structure classes for this?
– Avoid class explosion. Same solution as for Customer
and Accounts?
9/28/01
F-28
One Solution
• Beverage abstract super-class
– Subclasses: HouseBlend, DarkRoast, Decaf,…
• Fields / Attributes:
– milk, soy, mocha, whip
• Methods / Operations:
– hasMilk(), setMilk(); hasSoy(), setSoy(); …
• Issues?
9/28/01
F-29
Problems with This Approach
• Price for condiments? Alter existing code
• New condiments? Add methods; alter cost()
operation in superclass
• New beverage like ice tea that shouldn’t have
whipped milk?
• Want a double mocha?
9/28/01
F-30
Decorator Design Pattern
• “Decorate” an object
– Wrappers: a object defined so that it encloses
another object
• Key points:
– Decorators have the same supertype as the
object they wrap.
So you can use a decorated object in the same
place as the original object (a la Liskov)
– Can use more than one decorator on an object
– Can decorate objects at run-time
9/28/01
F-31
Decorators in Java I/O
• Used for input and output file streams
• Many stream types are wrappers
– Add extra functionality, e.g. push-back, line-numbering,
buffering, etc.
– Create by using “more basic” file-stream object in
constructor
– Can used a wrapped-stream where you’d use any stream
• See Java API:
http://java.sun.com/j2se/1.4.2/docs/api/java/io/FilterInp
utStream.html
• Also used in Java Swing
9/28/01
F-32
Decorators in Java I/O
FileInputStream istream = new FileInputStream(“foo.txt”);
BufferedInputStream bstream =
new BufferedInputStream(istream);
9/28/01
F-33
Issues with Decorators
• Disadvantages:
– May add many classes, makes package hard to
understand
• Like Java I/O streams
– Client code should not rely on knowing a
reference’s specific concrete class
• May get wrapped. Wrapping intended to
transparent to client code.
– Creating new objects could be more complex
• A factory pattern class
9/28/01
F-34
Swing Examples of Decorators
• Example 1: Button with a diagonal line
– http://www.ideas2work.com/decorator-java.html
– Note: quick read, but not a lot of explanation of
Swing and how buttons are drawn or
components
• Example 2 & 3: Component border, minimize
– http://www.onjava.com/pub/a/onjava/2003/02/05/decorator.html?page=1
– Better explanation, especially of
• Decorator pattern
• Inheritance vs. decoration
• how components are
composed and painted in Swing
9/28/01
F-35