Transcript Document

Design Patterns
Contents
•Terminology in object-oriented design
•Mechanisms for reuse
•Designing for change
•Categorizing and selecting design patterns
Reference:
Design Patterns; Gamma, Helm, Johnson, Vlissides
Terminology
1. Object Interface
a. Signature of a method
2. Toolkits
3. Frameworks
4. Design Patterns
Object Interface
Class diagram
Name
attributes
methods
Every method in the class has its
own unique signature
return_type name
(parameter types)
The set of all signatures defined by
an object’s methods or operations
is called the object interface.
This interface characterizes the
complete set of requests that can be
sent to the object.
Specifying Object Interfaces
Signature of a method:
•name
ClassA
•parameters
int metod1(int param);
•return type
void resize( );
Interface
ClassB
int metod1(int param);
void resize( );
int metod1(int param);
void resize( );
Possible message recipients
Implementation of an Interface in C++
Interface provided by an
abstract class
Concrete realizations
receive the messages
Circle
Shape
virtual double area( ) = 0;
double area( ) ;
void draw( ) ;
void resize(int scale) ;
virtual void draw( ) = 0;
virtual void
resize(int scale) = 0;
Rectangle
void draw( ) ;
double area( ) ;
void resize(int scale) ;
Class Hierarchy
Shape
Rectangle
Square
Circle
Messages directed to a Shape
object can be received by
instances of any of these
concrete classes.
Toolkits
A toolkit is a set of related and reusable classes designed to
provide general-purpose functionality. – Gamma et al.
Examples:
Collection classes: Vector, Stack, Queue, List, etc:
Found in libraries such as java.util or the C++ STL
The Java or C++ stream library
Frameworks
A framework is a set of cooperating classes that make up a
reusable design for a specific class of software. – Gamma, et al.
The framework dictates the architecture of your application.
It captures the design decisions that are common to the
domain of the application. It establishes the partitioning into
classes and objects and the pattern of collaboration between
objects.
Frameworks promote design reuse
Example: the java awt and swing packages
Design Patterns
Patterns capture solutions to particular design problems.
They provide for the reuse of successful designs.
Incorporate design experience.
A design pattern is like a template that can be
applied in many different situations.
A design pattern provides an abstract description of a
design problem and how a general arrangement of
elements (classes and objects) solves it. – Gamma et al.
Design Patterns
Design Patterns emphasize “design for
maintainability”. Good design not only addresses
the current problem, but also anticipates the need
for future additions and modifications.
Elements of a Design Pattern
Pattern Name
Names allow the designer to work at a higher level of
abstraction. Names make it easier to talk about and think about
designs.
Description of the problem
Describes the problem and its context.
The Solution
Describes the classes that make up the design, their
relationships, and collaborations.
The Consequences
The results and tradeoffs of applying the pattern.
Categories of Design Patterns
Purpose
Design Pattern
Creational
Abstract Factory
Builder
Factory Method
Structural
Behavioral
{Partial listing}
Adapter
Aspects that can vary
Families of product objects
Creation of a composite object
Subclass of object instantiated
Interface to an object
Facade
Interface to a subsystem
Flyweight
Storage costs of objects
Proxy
How an object is accessed
Command
When & how a request is fulfilled
Iterator
Traversal of elements in an
aggregate
Notation
Symbol
Meaning
Aggregation
B
A
Object A instantiates B
A
B is a subclass of A
B
Comment box
ClassName
class method
o
Implementation pseudocode
Iterator Pattern
Intent
Provide a way to access the elements of an aggregate object
sequentially without exposing its underlying representation.
•Supports multiple traversals of aggregate objects.
•Provides a uniform interface for traversing different aggregate
structures (it supports polymorphic iteration).
Iterator Pattern
Structure
Aggregate
Client
createIterator( )
Iterator
first( )
next( )
isDone( )
currentItem( )
ConcreteAggregate
ConcreteIterator
createIterator( )
//client code
return new ConcreteIterator(this)
Aggregate myList = new ConcreteAggregate( );
Iterator itr = myList.createIterator( );
Iterator Pattern
Participants
•Iterator
-- defines an interface for accessing and traversing elements
•ConcreteIterator
-- implements the Iterator interface
-- keeps track of the current position in the traversal of the aggregate
•Aggregate
-- defines an interface for creating an Iterator object
•ConcreteAggregate
-- implements the Iterator creation interface to return an instance
of the proper ConcreteIterator
Iterator Pattern
Consequences
1. It supports variations in the traversal of an aggregate.
For example, code generation may traverse the parse
tree inorder or preorder. Iterators make it easy to
change the traversal. Just replace the iterator
instance with a different one.
2. Iterators simplify the Aggregate interface. Iterator’s
traversal interface obviates the need for a similar
interface in Aggregate.
3. More than one traversal can be pending on an aggregate.
Iterator Pattern
Iterators in Java
In object-oriented programming one distinguishes
between the container object that holds data and an
Iterator object that traverses the container and visits
the data items.
To use an Iterator perform the following steps:
1.
Obtain an iterator from the Collection object (List) by using a
method (in the interface) iterator( ). This method call returns an
iterator object and sets it to read the first element in the list.
2.
Get the next object in sequence with method next( ).
3.
See if there are any more elements in the sequence with a call to
hasNext( ).
4.
You may remove the last item returned by the iterator from the list
with a call to remove( )
Iterator Pattern
Iterator in Java -- in Java we have the following methods
that implement the Design Pattern Iterator
Iterator itr = containerObject.iterator( );
Implements the createIterator( ) in the Iterator Pattern
itr.hasNext( )
Java implementation of isDone( )
itr.next( )
Combines methods currentItem( )
and next( ) specified in the Pattern
Iterator Pattern
Example of a polymorphic iterator
With an iterator one can write generic methods to handle any collection
public class Printer {
public static void printAll (Iterator e) {
while (e.hasNext( ) )
System.out.print (e.next( ) + “ ” );
System.out.println( );
The method receives an
iterator object as its argument
with no distinction made
about what collection
produced it.
}
public class FrogPond {
public static void main(String [ ] args) {
ArrayList v = new ArrayList( );
for (int i = 0; i < args[0]; i++)
v.add(new Frog(i));
Printer.printAll(v.iterator( ));
}
}
Obtain an iterator from the ArrayList
and pass it to the Printer
Command Pattern
Intent
Encapsulate a request as an object letting you:
•Parameterize clients with different requests
•Queue or log requests
•Support undo operations
Command Pattern
Structure
Client
Invoker
Command
execute()
Receiver
action()
ConcreteCommand
execute() o
state
receiver_action()
Command Pattern
Participants
•Command
-- declares an interface for executing an operation
•ConcreteCommand
-- defines a binding between a Receiver object and an action
--implements execute() by invoking the corresponding
operation(s) on Receiver
•Client (Application)
-- creates a ConcreteCommand object and sets its receiver
•Invoker (Menuitem)
--asks the command to carry out the request
•Receiver (Document)
--knows how to carry out the request. (Any class may
serve as Receiver)
Command Pattern
Collaborations
aReceiver
aClient
aCommand
anInvoker
new Command
add(aCommand)
execute( )
action( )
Command Pattern
Collaborations
1. The Client creates a ConcreteCommand object and
specifies its receiver.
2. An Invoker object stores the ConcreteCommand object.
3. The invoker issues a request by calling execute( ) on the
command. When commands are undoable,
ConcreteCommand stores state for undoing prior to
invoking execute( ).
4. The ConcreteCommand object invokes operations on its
receiver to carry out the request.
Command Pattern
Consequences
1. Command decouples the object that invokes the
operation from the one that knows how to perform it.
2. Commands are first-class objects. They can be
manipulated and extended like any other object.
3. Its easy to add new Commands, because you don’t have
to change existing classes.
4. Commands can be assembled into a composite command.
Invoker
App
Menu
run( )
Stack
Abstract
Command
MenuItem
Command
select( );
execute( )
Push
Pop
execute()
Receiver
Command Pattern Implemented in C++
Concrete Commands
item ask( )
S-> push(item)
Using Command Pattern in Java
Let’s redo the previous example in Java. The Command Design Pattern can
be implemented within the framework provided in the swing classes.
Inheritance Structure
JMenu
JMenuBar
JComponent
AbstractButton
JPopupMenu
JMenuItem
JRadioButtonMenuItem
JCheckBoxmenuItem
Notice that a JMenu is itself a menu item. This allows one to place a submenu
inside of another menu.
Command Pattern in Java
Extend class JMenuItem to pass in a Command object in the constructor, and add a
method select( ) that calls the execute( ) method of the embedded command.
class MyJMenuItem extends JMenuItem{
Command theOrder;
public MyJMenuItem(String str, Command c) {
super(str);
theOrder = c;
}
public void select( ) {
theOrder.execute( );
}
}
Command Pattern in Java
In the application (JApplet) method actionPerformed( ) determines the source of
the event (menu item selected) and executes its method select.
public void actionPerformed(ActionEvent e) {
MyJMenuItem theItem = (MyJMenuItem)(e.getSource( ));
theItem.select( );
}
Command Pattern in Java
Commands are OBJECTS that implement the Command interface.
interface Command {
public void execute( );
}
class Pop implements Command{
Stack theStack;
public Pop(Stack s) {
theStack = s;
}
public void execute( ) {
theStack.pop( );
}
}
Interface Command with (abstract) method
execute
Object Pop a concrete Command
The Stack object that the Command directs is
passed in as a parameter in the constructor
Concrete Command objects override method
execute( )
Invoker
JApplet
JMenu
run( )
Abstract
Command
JMenuItem
Command
select( );
execute( )
Stack
Push
Pop
execute()
Receiver
Command Pattern Implemented in Java
Concrete Commands
item ask( )
S-> push(item)
Further Information about Design Patterns
Design Patterns Home Page
Links of particular interest:
Doug Lea’s FAQ on Design Patterns
Setting up a Design Pattern study group