Date post: | 25-Dec-2015 |
Category: |
Documents |
Upload: | laureen-dawson |
View: | 243 times |
Download: | 2 times |
Design Patterns
CS 124
Reference: Gamma et al(“Gang-of-4”), Design Patterns
Pattern: some definitions
a combination of qualities, acts, tendencies, etc., forming a consistent or characteristic arrangement: the behavior patterns of teenagers.
an original or model considered for or deserving of imitation: our constitution has been a pattern for those of many new republics.
anything fashioned or designed to serve as a model or guide for something to be made: a paper pattern for a dress.
Definitions extracted from dictionary.com
Design Pattern
The notion of pattern as it applies to OO software development
Solution to a particular kind of problem How to combine classes and methods Based on design experience Use requires understanding of the appropriate
problem and being able to recognize when such problems occur
Reuse solutions from the past It is not code reuse, it is experience reuse
Patterns in other professions
Other professions have developed patterns and jargon for these well-tested patterns
Example: writers/novelists: “Tragically-flawed hero”, “romantic novel”
Other professions Architects/building engineers Con-artists (see Ocean’s 11 movies)
Design Patterns: the highest form of reuse and abstraction
Specific concrete Code Code Snippets Functions / Methods
Generalized and Reusable Code Classes, Templates, Code library, API
Reusable concepts Data Structures, Algorithms
Patterns How / When to apply these concepts, Design Patterns
Design Patterns Name Intent/Problem
Situation (problem) and context When to apply the pattern; conditions
Solution Elements that make up the design, relationships,
collaboration; more a template rather than a concrete solution
How the general arrangement classes and objects solves it UML diagrams (class relationships and responsibilities)
Consequences variations, tradeoffs, cost-benefit
How to select design patterns
Consider how the design patterns solve design problems
Scan intent section Consider how patterns interrelate Study patterns of like purpose Examine cause of redesign Consider what should be variable in design (what
you might want to change without redesign): Encapsulate the concept that varies
How to use a design pattern
Read up on the pattern Study structure, collaboration, participants Look at sample code Choose names of participants meaningful in the
application context Define classes Define application specific names for operations in
the process Implement the operations
Some Patterns for Discussion
Singleton Factory Method Adaptor Iterator
Singleton Intent
ensure a class has only one instance, and provide a global point of access to it
Motivation Important for some classes to have exactly one instance.
E.g., although there are many printers, should just have one print spooler
Ensure only one instance available and easily accessible global variables gives access, but doesn’t keep you from
instantiating many objects Give class responsibility for keeping track of its sole
instance
Design Solution
Defines a getInstance() operation that lets clients access its unique instance
May be responsible for creating its own unique instance
Singleton
-uniqueinstanceSingleton data…
+getInstance()Singleton methods…
Recall that an underlined method means “static”
Singleton Example (Java)
Database
Database
-Database DBinstance attributes…
+Database getDB()instance methods…
public class Database {private static Database DB; ...private Database() { ... }public static Database getDB() { if (DB == null) DB = new Database(); return DB;} ...}
In application code…Database db = Database.getDB();db.someMethod();
Implementation Declare all of class’ constructors private
prevent other classes from directly creating an instance of this class
Hide the operation that creates the instance behind a class operation (getInstance)
Variation: Since creation policy is encapsulated in getInstance, possible to vary the creation policy
Singleton Consequences
Ensures only one (e.g., Database) instance exists in the system
Can also use this pattern to control fixed multiple instances
Much better than the alternative: global variables
Factory Method
Intent: provide an interface for creating objects without specifying their concrete classes
Example: Stacks, Queues, and other data structures Want users to not know or care how these structures are
implemented (separation) Example: UI toolkit to support multiple look-and-feel
standards, e.g., Motif, PM Abstract class for widget, supporting class for specific
platform widget
Design Solution forFactory Method
Factory
createProduct():Product
<<interface>> Product
abstract methods
ConcreteProdA
methods
ConcreteProdB
methods
Client
Note: this is anabbreviated design
Participants Factory
implements the operations to create concrete product objects
(Abstract) Product: declares an interface for a type of product object
Concrete Product defines a product object to be created by the
corresponding concrete factory implements the abstract product interface
Client: uses only Factory and Abstract Product
Factories in Java
Stack is an Interface ArrayStack and LinkedStack implement Stack StackFactory returns objects of type Stack through
its factory methods Select the appropriate concrete Stack class class
If using info from requesting client, can hardcode selection logic and choice of product objects
Use Hashed Adapter Pattern to separate selection logic for factories from the data it uses to make the selection
Factory Method Consequences
Factory class or method can be altered without affecting the application Concrete classes are isolated
Factory class can be responsible for creating different types of objects e.g., DataStructure factory that returns stacks,
queues, lists, etc. “product families” (see Abstract Factory pattern) creational logic
determining object type based on certain criteria
Coupling One of the goals of Design Patterns is the idea of
loose-coupling or de-coupling reducing or removing class dependencies throughout the
system For example, Factory removes the dependency on the
specific subclasses generated by the Factory from the rest of the system
instead the system is dependent on the single interface type that is generated by the Factory
Loosely coupled or decoupled code is easier to reuse since the code has fewer dependencies on other code
Kinds of Patterns
Singleton and Factory Method are examples of Creational Patterns
Other kinds of patterns Structural: concerns object structure;
e.g., Adapter Behavioral: concerns object interaction and
distribution of responsibilities;e.g., Iterator
Adapter Intent: Adapter lets classes work together that couldn’t otherwise
because of incompatible interfaces.
Motivation: Sometimes, a class that is designed for reuse isn’t reusable only because its interface doesn’t match the domain-specific interface an application requires. e.g. drawing editor that allows users to draw and edit shapes.
Has a TextShape subclass that is hard to implement. Fortunately there are pre-existing classes like TextView that implements the complexities; problem is incompatibility.
It would not make sense if we have to modify the reusable class so as to conform to the client interface. Built-in; no source code
Two forms of the Adapter Pattern
Object Adapter pattern Concerned with object composition. Implements the interface that the client expects and
creates an adaptee instance within the adapter class Implements client’s methods by making calls to a
physical instance of the adaptee object.
Client Expected
+ expectedMethod()
ObjectAdapter
+ void : expectedMethod()
- Adaptee : adaptee
void expectedMethod() { adaptee.specificMethod();}
1 Adaptee
+ void : specificMethod()
1
Two forms of the Adapter Pattern
Class Adapter Pattern A class adapter uses multiple inheritance to adapt one
interface to another. Inherits the client interface and the adaptee’s
implementation.
Client Expected
+ expectedMethod()
ClassAdapter
+ void : expectedMethod()+ void : specificMethod()
void expectedMethod() { specificMethod();}
1 Adaptee
+ void : specificMethod()
Comparison of Applicability & Consequences
Use adapter pattern when: Using an existing class that does not match with the one you
need (object adapter only) reusing several existing class
Impractical to adapt each by subclassing every one of them
Consequences:
Object Adapter- Lets a single adapter work with
many adaptees (adaptee itself and subclasses)
- Harder to override adaptee behavior
Class Adapter- Class adapter won’t work with
adaptee’s subclasses- Easier to override adaptee’s behavior,
since adapter is a subclass of adaptee- Can have unforseen consequences,
Adapter can be placed anywhere the Adaptee can due to inheritance
Iterator Pattern
Intent: provide a way to access the elements of an aggregate object sequentially without expressing its underlying representation
Example: iterators for Java collections or C++ STL containers Note that you can have several iterator objects for
a container and that the iterators are separate classes
<<interface>>Collection
iterator() : IteratorIF…
<<interface>>IteratorIF
hasNext() : booleannext() : Item
Collection IteratorFetches from
Creates
Iterators in Java
Iterators are used a lot with Java collection objects e.g. Lists, Sets and Maps
By calling the iterator() method on the List/Set or on the result of Map.values() you can go through all the elements via the next() method
Note: order of insertion is not necessarily going to be followed by the iterator, it only guarantees that everything will come out.
Creational Patterns
Abstract Factory Builder Factory Method Prototype Singleton
Structural Patterns
Adapter Bridge Composite Decorator Façade Flyweight Proxy
Behavioral Patterns
Chain of Responsibility Command Interpreter Iterator Mediator Memento And a few more …
Summary
Main point: to recognize that there are proven solutions to problems that a designer/ programmer may encounter Solutions are results of others’ experiences Towards “standard approaches”
Search for such solutions first Although there is some merit attempting to create the
solution yourself
Becoming a design architect Up Next: More patterns