Upload
clare-bond
View
218
Download
3
Embed Size (px)
Citation preview
Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Ojitha KumanaykaOjitha KumanaykaTraining Group SL 2005Training Group SL 2005
2Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Ralph Johnson
Richard Helm
Erich Gamma
John Vlissides
Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley, 1995)
3Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
4Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Production based Economy
Production = High Effort +
Less productive
Planning + Design + Production = Less Effort + High productive
5Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
AgendaAgendaAgendaAgenda• IntroductionIntroduction•Pattern StructurePattern Structure•MVC modelMVC model•Purpose Purpose •ScopeScope•Patterns CatalogPatterns Catalog
• CreationalCreational•Factory MethodFactory Method•Abstract FactoryAbstract Factory•BuilderBuilder•PrototypePrototype•SingletonSingleton
•StructuralStructural•AdapterAdapter•BridgeBridge•CompositeComposite•DecoratorDecorator•FaçadeFaçade
6Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Presentation FrameworkPresentation FrameworkPresentation FrameworkPresentation Framework•FlyweightFlyweight•ProxyProxy
•BehavioralBehavioral•InterpreterInterpreter•Template methodTemplate method•Chain of responsibilityChain of responsibility•CommandCommand•IteratorIterator•MediatorMediator•MementoMemento•ObserverObserver•StateState•StrategyStrategy•VisitorVisitor
•First step to frameworkFirst step to framework•Developing frameworks-InheritanceDeveloping frameworks-Inheritance•Developing frameworks-component libraryDeveloping frameworks-component library•Add component to component libraryAdd component to component library
7Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Introduction to Design Patterns & pattern-oriented FrameworksIntroduction to Design Patterns & pattern-oriented Frameworks
– What is pattern ?“Each pattern describes a problem which occur over and over again in our environment. And then describes the core of the solution to that problem , in such a way that you can use this solution a million times over , without doing twice.”
Christopher Alexander, pattern language 1977
– What is Framework ?“A framework is set of cooperating classes that make up a reusable design for a specific class of software”
Ralph E. Johnson and Brian Foote, Designing Reusable Objects,
1988
8Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Pattern structurePattern structure
– Pattern nameThis is a handle can be used to address design
problem in high level of abstraction.
– ProblemIt explain problem and its context. Sometimes
problem may contain list of conditions.
– SolutionDescribes the elements that make up the design, their
relationship and collaborations.
– ConsequencesResults and trade-offs of applying pattern
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
9Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
MVC ModelMVC Model
• Model• View• controller
benefits
• Reusability
• Flexibility
• Extendibility
• Portability
10Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
PurposePurpose
– Creational Process of object creation
– Structural Composition of classes or objects
– BehavioralClasses or objects interact and distribute
responsibilities
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
11Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
ScopeScope
– ClassRelationship between classes and their sub classes.
These relationships are established through inheritance because they are statically fixed at compilation time
– ObjectRelationships between objects.
These relationships can be changed at runtime and are more dynamic
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
12Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Pattern catalogPattern catalogPattern catalogPattern catalog
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
13Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Creational PatternsCreational Patterns
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Creational patterns make a system independent of how its objects are created, composed and represented.
- Encapsulate knowledge about which concrete classes the system use
- Hide how objects of concrete classes are created
NOTE:
Creational class patterns defer some part of object creation to subclasses
Creational object patterns defer some part of object creation to another object.
14Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Synergy of Creational PatternsSynergy of Creational Patterns
15Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Factory MethodFactory Method
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Define and interface to creating an object, but subclasses decide which class has to be initiated. This can be solved by using factory method .
Applicability
• The class can not anticipate the class of objects it must create
• A class wants its subclasses to specify the objects it creates
• Class delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.
Consequences
• Eliminate application specific detail form the high level abstraction and only negotiate with abstract classes .
• Disadvantage is anyway client has to sub class form abstract class
16Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Factory Method Case study : Document Application Factory Method Case study : Document Application
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
MyApplication
CreateDocument()
TXT
Open()Close()
RTF
Open()Close()
Application
CreateDocument()OpenDocument()
Document
Open()Close()Save()Revert()
17Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Abstract FactoryAbstract Factory
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Provide an interface for creating families of related or dependent objects without define their concrete classes.
Applicability• System should independent form its products are created, composed,
and represented• A system should be configured with one more families of same type of
products• A family of related product objects is designed to be used together and
need to enforce this constrain.• Reveal only interfaces of class library(eg: framework)Consequences• Isolate concrete classes• It makes exchanging product families easy• It promote consistency among products• Supporting new kind of product if difficult
18Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Abstract Factory case study: User InterfaceAbstract Factory case study: User Interface
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
GnomeWidgetFactory
CreateScrollBar()CreateWindow()
KDEWidgetFactory
CreateScrollBar()CreateWindow()
GnomeWindow KDEWindow
GnomeScrollbarKDEScrollbar
WidgetFactory
CreateScrollBar()CreateWindow()
Window
Client
Scrollbar
19Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
BuilderBuilder
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Separate the construction of a complex object from its representation so that the same construction process can create different representations
Applicability
• The algorithm for creating a complex object should be independent of the parts that make up the object and how they are assembled.
• The construction process must allow different representations for the object that constructed.
Consequences
• It lets you vary a product’s internal representation
• It isolates code for construction and representation
• It gives finer control over the the construction process
20Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Builder case study : RTF ReaderBuilder case study : RTF Reader
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
21Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
PrototypePrototype
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
Applicability
• When the classes to instantiate are specified at run-time, for example, by dynamic loading
• To avoid building a class hierarchy of factories that parallels the class hierarchy of products
Consequences
• Same consequences of Abstract Factory and Builder
• Adding and removing products at run-time
• Specifying new objects by varying values.
• Reduced sub-classing
22Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Prototype case study: Money ExchangePrototype case study: Money Exchange
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Money
draw()clone()getPicture()
Map
draw()clone()getLocation()
Exchange
manipulate()setRate()getRate()
Graphic
draw()clone()
23Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
SingletonSingleton
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Ensure a class only has one instance, and provide a global point of access to it
Applicability
• There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
• When the sole instance should be extensible by sub-classing, and clients should be able to use an extended instance without modifying their code
Consequences
• Control access to sole instance
• Reduce name space
24Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Structural PatternsStructural Patterns
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Classes and objects are composed to form larger structures
Note
• Structural class patterns use inheritance to compose classes
• Structural object patterns describe ways to assemble objects
25Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Synergy of Structural PatternsSynergy of Structural Patterns
26Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
AdapterAdapter
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
Applicability• The already developed classes which can not be used with application
because interfaces are not match• Integrate functionality which is incompatible with application
(Pluggable adapter).Consequences• A class adapter won’t work when we want to adapt a class and all its
subclasses• Adapter class override some Adaptee behavior• Single adapter object will work with many Adaptee objects• It harder to override Adaptee behavior
27Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Adapter Example: Electrical MotorAdapter Example: Electrical Motor
28Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Adapter pattern(class) case study: Drawing EditorAdapter pattern(class) case study: Drawing Editor
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
DrawingEditorShape
boundingBox()
Line
boundingBox()
TextShape
boundingBox()create()edit()delete()append()
RTFText
create()edit()delete()append()
- - - - - -
29Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Adapter pattern(object) case study: Drawing EditorAdapter pattern(object) case study: Drawing Editor
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
DrawingEditorShape
boundingBox()
Line
boundingBox()
TextShape
boundingBox()
RTFText
create()edit()delete()append()
RTFText.append()
30Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
BridgeBridge
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Decouple an abstraction from its implementation so that the two can vary independently
31Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Clock
32Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Clock ClockImpl
33Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Bridge Pattern case study : UIBridge Pattern case study : UI
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Window
drawText()drawRect()
XWindow PMWindow
Window
drawText()drawRect()
PMWindow XWindow IconWindow
drawBorder()
XIconWindow PMIconWindow
34Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Bridge Pattern case study : UI continue…Bridge Pattern case study : UI continue…
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
IconWindow
drawBorder()
TransientWindow
drawCloseBox()
XWindowImp
drawText()drawLine()
PMWindowImp
drawText()drawLine()
Window
drawText()drawRect()
WindowImp
drawText()drawLine()
Window
drawText()drawRect()
35Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
BridgeBridge
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Applicability
• Avoid permanent binding abstraction and its implementation
• When need to sub-class both the abstraction and implementation
• To avoid impact on client by changing implementation
• Completely hide implementation from abstraction
Consequences
• Decupling interface and implementation
• Improved Extendibility
• Hiding implementation details from clients
36Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
CompositeComposite
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Composite objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
37Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Composite: ExamplesComposite: Examples
38Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Composite pattern case study: CASE TOOLComposite pattern case study: CASE TOOL
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Drawing
draw()addGraphic()removeGraphic()getChildren()
Graphic
draw()addGraphic()removeGraphic()getChildren()
Line
draw()
Curve
draw()
house : Drawing
curve1 : Curve
line2 : Line
room : Drawing
line1 : Line
line3 : Line
line4 : Line
39Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
CompositeComposite
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Applicability
• To represent part-whole hierarchies of objects
• To ignore the deference between compositions of objects and individual objects.
Consequences
• Define class hierarchies of primitive objects and composite objects.
• Make the client simple because client treat composite and primitives uniformly
• Easy to add new primitive or composite
• It is harder to restrict the components of a composite
40Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
DecoratorDecorator
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub-classing for extending functionality
41Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Decorator case study: Test ViewerDecorator case study: Test Viewer
ScrollDecorator
draw()scrollTo()
BorderDecorator
draw()drawBorder()
TextView
draw()
Decorator
draw()
VisualComponent
draw()
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
42Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
DecoratorDecorator
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Applicability
• To add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects.
• To withdraw responsibilities
• To avoid sub-classing to add extensions.
Consequences
• More flexibility than static inheritance
• Decorates which are independent from class hierarchy.
• Play- as-you go approach to adding responsibilities
• Lost of little manageable objects
43Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
FaçadeFaçade
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use.
44Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Façade case study: B2BFaçade case study: B2B
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
SubSystem
ParserResposne
SAXRequest
client
1 2
35
DOM
4SubSystem
Parser
Resposne
SAXRequest DOM
Client
Facade1
2
35 4
45Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
FaçadeFaçade
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Applicability
• To provide simple interface to complex subsystem.
• To decouple subsystem form clients and other subsystems
• As entry point
Consequences
• Make subsystem easier to use without deep knowledge about its process sequence.
• Decoupling enhance more independency to both client and subsystem
• But this is extra layer which intercept client from subsystem.
46Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
FlyweightFlyweight
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Use sharing to support large number of fine-grained objects efficiently
47Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Flyweight Pattern case study: Text EditorFlyweight Pattern case study: Text Editor
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
48Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
FlyweightFlyweight
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Applicability
• When application use large number of objects
• To minimize storage cost
• To replace group of objects with shareable objects
• Distinct objects made independent from the application
Consequences
• Minimize storage cost by reducing total number of objects
• Increase amount of intrinsic state per object
• But run-time cost associate with transferring, finding, and computing extrinsic state is high
49Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
ProxyProxy
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Provide a surrogate or placeholder for another object to control access to it
50Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Vendor
Local
Representative
Remote ProxyRemote Proxy
51Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
ProxyProxy
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Applicability
• Remote proxy
• Virtual proxy
• Protection proxy
• Smart reference
Consequences
• A remote proxy can hide the fact that an object resides in a different address space
• A virtual proxy can perform optimization such as creating an object on demand
• Both protection proxies and smart references allow additional housekeeping tasks when an object is accessed.
52Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Games to playhttp://www.objectventure.com/gameshow/ Good paperhttp://www.cmcrossroads.com/bradapp/docs/patterns-intro.html
GameGame
53Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Behavioral PatternsBehavioral PatternsBehavioral PatternsBehavioral Patterns
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
• The Behavioral class patterns use inheritance to describe • algorithms and
• flow of control
• whereas the Behavioral object patterns describe how a group of objects cooperate to perform a task that no single object can carry out alone.
54Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Synergy of Behavioral PatternsSynergy of Behavioral PatternsSynergy of Behavioral PatternsSynergy of Behavioral Patterns
55Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Chain Of ResponsibilityChain Of ResponsibilityChain Of ResponsibilityChain Of Responsibility
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
56Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Case study: context sensitive Help SystemCase study: context sensitive Help SystemCase study: context sensitive Help SystemCase study: context sensitive Help System
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
aPrintDialog
aPringButton
anApplication
57Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Chain Of ResponsibilityChain Of ResponsibilityChain Of ResponsibilityChain Of Responsibility
Applicability
• more than one object may handle a request, and the handler isn't known a prior. The handler should be ascertained automatically
• you want to issue a request to one of several objects without specifying the receiver explicitly
• the set of objects that can handle a request should be specified dynamically Consequences
• Reduced coupling
• Added flexibility in assigning responsibilities to objects
• Receipt isn't guaranteed
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
58Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Command PatternCommand PatternCommand PatternCommand Pattern
Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
59Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Case study: Menu SystemCase study: Menu SystemCase study: Menu SystemCase study: Menu SystemMenu
MenuItem
Document
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
60Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Command PatternCommand PatternCommand PatternCommand PatternApplicability
• parameterize objects by an action to perform
• A Command object can have a lifetime independent of the original request specify, queue, and execute requests at different times.
• The Command's Execute operation can store state for reversing its effects in the command itself by supporting to undo.
• The Command pattern offers a way to model transactions
• Recovering from a crash involves reloading logged commands from disk and re-executing them with the Execute operation.
Consequences
• Command decouples the object that invokes the operation from the one that knows how to perform it.
• Commands are first-class objects. They can be manipulated and extended like any other object.
• You can assemble commands into a composite command.
• It's easy to add new Commands, because you don't have to change existing classes.
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
61Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Iterator PatternIterator Pattern
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
62Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Dynamic behavior of Iterator PatternDynamic behavior of Iterator Pattern
63Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Iterator PatternIterator Pattern
Applicability
• to access an aggregate object's contents without exposing its internal representation.
• to support multiple traversals of aggregate objects.
• to provide a uniform interface for traversing different aggregate structures. (that is, to support polymorphic iteration)
Consequences
• It supports variations in the traversal of an aggregate
• Iterators simplify the Aggregate interface
• More than one traversal can be pending on an aggregate.
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
64Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
InterpreterInterpreterInterpreterInterpreterGiven a language, define a representation for its grammar along with an
interpreter that uses the representation to interpret sentences in the language.
Applicability
• the grammar is simple
• efficiency is not a critical concern
Consequences
• It's easy to change and extend the grammar
• Implementing the grammar is easy, too
• Complex grammars are hard to maintain
• Adding new ways to interpret expressions GOF, Design Patterns: Elements of Reusable
Object Oriented Software, 1995
65Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Interpreter case study: Language Interpreter case study: Language GrammarGrammarInterpreter case study: Language Interpreter case study: Language GrammarGrammar
• expression ::= literal | alternation | sequence | repetition | '(' expression ')'
• alternation ::= expression '|' expression
• sequence ::= expression '&' expression
• repetition ::= expression '*'
• literal ::= 'a' | 'b' | 'c' | ... { 'a' | 'b' | 'c' | ... }*
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
Symbols on the right-hand side of the rule are instance variables of these classes.
classes represent each grammar rule.
66Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Raining & (dog | cat )
Interpreter ExampleInterpreter ExampleInterpreter ExampleInterpreter Example
67Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
• expression ::= <command> | <sequence> | <repetition>
• command ::= right | quack | fly
• sequence ::= <expression> ‘;’<expression>
• repetition ::= while ‘(’ <variable> ‘)’<expression>
• variable ::= [A-Z, a-z]
Quack; // …and then quack
right; // turn rightwhile (daylight) fly;// fly all day
command
repetition
variablesequence
expression+interpret(in ctx : context)
Expression
+interpret(in ctx : context)
-variable : Variable-expression : Expression
Repetition
+interpret(in ctx : context)
Variable
+interpret(in ctx : context)
-expression1 : Expression-Expression2 : Expression
Sequence
*
*
*
**
*
+interpret(in ctx : context)
Command
+interpret(in ctx : context)
QuackCommand
+interpret(in ctx : context)
RightCommand
+interpret(in ctx : context)
FlyCommand
68Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Mediator PatternMediator PatternMediator PatternMediator Pattern
Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
69Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Mediator Pattern case study: Dialog EntryMediator Pattern case study: Dialog EntryMediator Pattern case study: Dialog EntryMediator Pattern case study: Dialog Entry
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
70Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Mediator PatternMediator PatternMediator PatternMediator PatternApplicability
• a set of objects communicate in well-defined but complex ways
• The resulting interdependencies are unstructured and difficult to understand.
• reusing an object is difficult because it refers to and communicates with many other objects.
• a behavior that's distributed between several classes should be customizable without a lot of subclassing.
Consequences
• It limits subclassing .
• It decouples colleagues
• It simplifies object protocols
• It abstracts how objects cooperate
• It centralizes control GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
71Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Memento PatternMemento PatternMemento PatternMemento Pattern
Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
72Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Memento Pattern : Drum BrakesMemento Pattern : Drum BrakesMemento Pattern : Drum BrakesMemento Pattern : Drum Brakes
73Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Memento Pattern: Drum BrakesMemento Pattern: Drum BrakesMemento Pattern: Drum BrakesMemento Pattern: Drum Brakes
74Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Memento PatternMemento PatternMemento PatternMemento Pattern
Applicability
• a snapshot of (some portion of) an object's state must be saved so that it can be restored to that state later, and
• a direct interface to obtaining the state would expose implementation details and break the object's encapsulation.
Consequences
• Preserving encapsulation boundaries
• It simplifies Originator
• Using mementos might be expensive
• Hidden costs in caring for mementos
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
75Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Observer PatternObserver PatternObserver PatternObserver Pattern
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
76Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Observer PatternObserver PatternObserver PatternObserver PatternApplicability
• When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.
• When a change to one object requires changing others, and you don't know how many objects need to be changed.
• When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don't want these objects tightly coupled.
Consequences
• Let vary subject and observer independently
• Subject can be reused without reusing their observers, and vice versa.
• Let add observers without modifying the subject or other observers.
• Abstract coupling between Subject and Observer
• Support for broadcast communication
• Unexpected updates GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
77Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
State PatternState PatternState PatternState Pattern
Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
78Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
State PatternState PatternState PatternState Pattern
79Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
• Draw diagram for TCP connection, possible states are• Established• Listen• Closed
State Pattern example: TCP connectionState Pattern example: TCP connectionState Pattern example: TCP connectionState Pattern example: TCP connection
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
80Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
State PatternState PatternState PatternState PatternApplicability
• An object's behavior depends on its state, and it must change its behavior at run-time depending on that state.
• Operations have large, multipart conditional statements that depend on the object's state. This state is usually represented by one or more enumerated constants. Often, several operations will contain this same conditional structure. The State pattern puts each branch of the conditional in a separate class. This lets you treat the object's state as an object in its own right that can vary independently from other objects.
Consequences
• It localizes state-specific behavior and partitions behavior for different states
• It makes state transitions explicit
• State objects can be shared
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
81Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Strategy PatternStrategy PatternStrategy PatternStrategy Pattern
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
82Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Strategy PatternStrategy PatternStrategy PatternStrategy Pattern
83Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Strategy PatternStrategy PatternStrategy PatternStrategy Pattern
Applicability
• Many related classes differ only in their behavior.
• You need different variants of an algorithm. For example, you might define algorithms reflecting different space/time trade-offs.
• An algorithm uses data that clients shouldn't know about. Use the Strategy pattern to avoid exposing complex, algorithm-specific data structures.
• a class defines many behaviors, and these appear as multiple conditional statements in its operations. Instead of many conditionals, move related conditional branches into their own Strategy class.
Consequences
• Families of related algorithms
• An alternative to subclassing
• Strategies eliminate conditional statements
• Clients must be aware of different Strategies
• Communication overhead between Strategy and Context GOF, Design Patterns: Elements of Reusable
Object Oriented Software, 1995
84Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Template PatternTemplate PatternTemplate PatternTemplate Pattern
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
85Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Template PatternTemplate PatternTemplate PatternTemplate Pattern
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
86Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Template PatternTemplate PatternTemplate PatternTemplate Pattern
Applicability
• To implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behavior that can vary.
• When common behavior among subclasses should be factored and localized in a common class to avoid code duplication.
• To control subclasses extensions. You can define a template method that calls "hook" operations (see Consequences) at specific points, thereby permitting extensions only at those points.
Consequences
• Template methods are a fundamental technique for code reuse. They are particularly important in class libraries, because they are the means for factoring out common behavior in library classes
• Template methods lead to an inverted control structure that's sometimes referred to as "the Hollywood principle," that is, "Don't call us, we'll call you"
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
87Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Visitor PatternVisitor PatternVisitor PatternVisitor Pattern
Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
88Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Visitor PatternVisitor PatternVisitor PatternVisitor Pattern
E -> VE -> E + EE -> E * EV -> a|b|c
GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995
89Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Visitor PatternVisitor PatternVisitor PatternVisitor Pattern
Applicability
• An object structure contains many classes of objects with differing interfaces.
• Many distinct and unrelated operations need to be performed on objects in an object structure, and you want to avoid "polluting" their classes with these operations.
• The classes defining the object structure rarely change, but you often want to define new operations over the structure.
• Changing the object structure classes requires redefining the interface to all visitors, which is potentially costly. If the object structure classes change often, then it's probably better to define the operations in those classes.
Consequences
• Visitor makes adding new operations easy
• A visitor gathers related operations and separates unrelated ones.
• Adding new ConcreteElement classes is hard GOF, Design Patterns: Elements of Reusable
Object Oriented Software, 1995
90Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
First step to FrameworksFirst step to Frameworks• Frameworks are reusable designs of all or part of a software system Frameworks are reusable designs of all or part of a software system described by a set of abstract classes and the way instances of those described by a set of abstract classes and the way instances of those classes collaborateclasses collaborate
• Framework reduce developing cost as well as size of the project Framework reduce developing cost as well as size of the project because it is reusablebecause it is reusable
•Unfortunately initial development of the framework is extra Unfortunately initial development of the framework is extra expenditure to the system and time consuming processexpenditure to the system and time consuming process
•Developers who should have prior experience in both development Developers who should have prior experience in both development technologies and design strategies(such as patterns)technologies and design strategies(such as patterns)
•Framework generalization will be increased with number of iterationsFramework generalization will be increased with number of iterations
91Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Developing frameworks - InheritanceDeveloping frameworks - Inheritance•Inheritance is the most expedient way of allowing users to change Inheritance is the most expedient way of allowing users to change code in object-oriented environment because most programming code in object-oriented environment because most programming languages are supporting this feature.languages are supporting this feature.
• But this will drive to high coupling and more programming work to But this will drive to high coupling and more programming work to create new classes. Inheritance is static and can not be changed in run-create new classes. Inheritance is static and can not be changed in run-time is other disadvantagetime is other disadvantage
•It is better to separate consistently changing part from constant partIt is better to separate consistently changing part from constant part
•Factory Method and Template Method are the patterns which can be Factory Method and Template Method are the patterns which can be used to inherit in this context because that will increase amount of used to inherit in this context because that will increase amount of reusable code.reusable code.
•One of the best example is MVC framework for GUI One of the best example is MVC framework for GUI
92Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Developing frameworks – Component LibraryDeveloping frameworks – Component Library•Abstract classes generally lie in the framework. Concrete classes Abstract classes generally lie in the framework. Concrete classes generally lie in applicationsgenerally lie in applications
•The component library can be created by accumulating all of the The component library can be created by accumulating all of the concrete classes created for various applications derived from the concrete classes created for various applications derived from the framework, but these concrete classes must reusable.framework, but these concrete classes must reusable.
•Large component libraries increase functionality but reduce the Large component libraries increase functionality but reduce the flexibility of the system because those are developed for specific flexibility of the system because those are developed for specific purposepurpose
•Framework must support off-the-shell libraries which are pluggable to Framework must support off-the-shell libraries which are pluggable to the application. Adapter pattern can be used in this context. However, the application. Adapter pattern can be used in this context. However, there should be suitable interface to adapt new components if you are there should be suitable interface to adapt new components if you are using class level adapter pattern.using class level adapter pattern.
93Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
Add components to Component LibraryAdd components to Component Library
It is recommended to use design patterns to create component for It is recommended to use design patterns to create component for component libraries because these components must be highly reusablecomponent libraries because these components must be highly reusableDesign Pattern Purpose
Strategy, Visitor Algorithms
Command Action
Bridge Implementation
Observer Responsible to change
Mediator Interactions between objects
Factory Method, Abstract Factory, Prototype
Object being created
Builder Structure being created
Iterator Traversal Algorithms
Adapter Object interface
Decorator, State Object behavior
94Copyright ©2004 Virtusa Corporation | CONFIDENTIAL
References
• GOF, Design Patterns: Elements of Reusable Object Oriented Software, 1995 Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (http://hillside.net )
• Head First Design Patterns, 2004 Freeman & Freeman
• Patterns and Software: Essential Concepts and Terminology (http://www.cmcrossroads.com/bradapp/docs/patterns-intro.html )
• JavaCamp (http://www.javacamp.org/designPattern/ )
• Design pattern Java Companion, J. W. Cooper (http://www.patterndepot.com/put/8/JavaPatterns.htm )
• Design Patterns in C# ( http://www.dofactory.com/Patterns/Patterns.aspx )
• Design pattern Quiz (http://home.earthlink.net/~huston2/dp/patterns_quiz.html )
• Non-Software Examples of Software Design Patterns(http://www2.ing.puc.cl/~jnavon/IIC2142/patexamples.htm )
• Java Design pattern tutorial (http://www.allapplabs.com/java_design_patterns/java_design_patterns.htm )