june 26, 20151 design patterns what is a design pattern -- each pattern describes a problem which...
Post on 21-Dec-2015
230 views
TRANSCRIPT
April 18, 2023 1
Design PatternsDesign Patterns What is a Design PatternWhat is a Design Pattern
-- Each pattern describes a problem which occurs 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 ever doing it the same
way twice(by Christopher Alexander)
Essential elements of a Design PatternEssential elements of a Design Pattern
- pattern name - problem - solution - consequence
April 18, 2023 2
Classification of design patternClassification of design pattern
According to its purposeAccording to its purpose
-- Creational
Factory Method, Abstract Factory, Builder, Prototype,Singleton
-- Structural
Adapter, Bridge, Composite, Decorator, Façade, Flyweight, Proxy
-- Behavioral
Interpreter, Template Method, Chain of Responsibility, command, Iterator, Mediator, Memento, Observer, State, Strategy, Visitor
April 18, 2023 3
Classification of design Classification of design pattern(continued)pattern(continued)
According to its scopeAccording to its scope
-- classclass
Factory Method, Adapter(class), Interpreter, Template Method
-- ObjectObject
The rest of the patterns
April 18, 2023 4
Patterns with possible use in Patterns with possible use in frameworkframework
Creational Patterns includingCreational Patterns including
Abstract Factory, Builder, Factory Method and Prototype
Behavioral PatternBehavioral Pattern
Command, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor
Notes: Factory Method and Template Method are class patterns
April 18, 2023 5
Abstract Factory Abstract Factory Object CreationalObject Creational
IntentIntent
Provide an interface for creating families of related or dependent objects without specifying their concrete class
MotivationMotivation
Consider a user interface toolkit that supports multiple look-and- feel standards, such as Motif and Presentation Manager. Different look-and-feels define different appearances and behaviors for user interface “widgets” like scroll bars, windows, and buttons. To be portable across look-and-feel standards, an application should not hard-code its widgets for a particular look-and-feel. Instantiating look-and-feel specific classes of widgets throughout the application makes it hard to change the look-and- feel later
April 18, 2023 6
Window
Client
MOtifWindowPMWindow
ScrollBar
MotifScorllBarPMScrollBar
WidgetFactory
createScrollBar()CreateWindow()
MotifWidgetFactory PMWidgetFactory
createScrollBar()CreateWindow()
createScrollBar()CreateWindow()
April 18, 2023 7
StructureStructure
April 18, 2023 8
CollaborationsCollaborations
-- -- Normally a single instance of a ConcreteFactory class is Normally a single instance of a ConcreteFactory class is created at run-time. This concrete factory creates product created at run-time. This concrete factory creates product objects having a particular implementation. To create objects having a particular implementation. To create different product objects, clients should use a different different product objects, clients should use a different concrete factoryconcrete factory
-- -- AbstractFactory defers creation of product objects to its AbstractFactory defers creation of product objects to its
ConcreteFactory subclassConcreteFactory subclass
April 18, 2023 9
Builder Builder -- Object Creational-- Object Creational
IntentIntent -- Separate the construction of a complex object from its
representation so that the same construction process can create different representation
MotivationMotivation -- A reader for the RTF(Rich Text Format) document exchange
format should be able to convert RTF to many text formats.
The reader might convert RTF documents into plain ASCII text or into a text widget that can be edited interactively. The problem, however, is that the number of possible conversions is open-ended. So it should be easy to add a new conversion without modifying the reader.
April 18, 2023 10
ConvertCccharacter(char)GetASCIITEXT()
ASCIIConverter TeXConverter
ConvertCccharacter(char)convertFontChange(Font)convertParagraph()GetTeXtext()
TeXTextASCIIText TexWidget
While(t=get the next token{Switch t.Type{CHAR:Builder->ConvertCharacter(t.Char)FONT:Builder->ConvertFontChange(t.Font)PARA:Biolder->convertParagraph()}}
TexWidgetConverter
ConvertCccharacter(char)convertFontChange(Font)convertParagraph()GetTextWidget()
ConvertCccharacter(char)convertFontChange(Font)convertParagraph()
TextConverterbuilders
RTFReader
ParseRTF()
builder
April 18, 2023 11
StructureStructure
April 18, 2023 12
CollaborationsCollaborations
-- The client creates the Director object and configures it with
the desired Builder object -- Director notifies the builder whenever a part of the product
should be built -- The client retrieves the product from the builder
April 18, 2023 13
Factory Method Factory Method Class CreationalClass Creational
IntentIntent Define an interface for creating an object, but let subclass
decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses
MotivationMotivation Frameworks use abstract classes to define and maintain
relationships between objects. A framework is often responsible for creating these objects as well.
Consider a framework for applications that can present multiple documents to the user. Tow key abstractions in this framework are the classes Application and Document. Both classes are abstract,and clients have to subclass them to realize their application-specific implementations. To create a drawing application,for example,we define the class DrawingApplciation and DrawingDocument. The Application class is responsible for managing Documents and will create them as required-when when the user selects Open or New from a menu, for example.
April 18, 2023 14
MyDocument
Document
Open()Close(0Save()Revert()
createDocument()NewDocument()openDocument()
Application
createDocument()
MyApplication
Document* doc= createDocument();Docs.Add(doc);Doc->open()
Return new MyDocument
docs
April 18, 2023 15
Structure
April 18, 2023 16
CollaborationsCollaborations
-- Creator relies on its subclasses to define the factory method so that it returns an instance of the appropriate ConcreteProduct
April 18, 2023 17
Prototype Prototype Object CreationalObject Creational
IntentIntent
Specify the kinds of Objects to create using a prototypical instance,and create new objects by copying this prototype
MotivationMotivation
You could build an editor for music scores by customizing a general framework for graphical editors and adding new objects that represent notes,rests, and staves. The editor framework may have a palette of tools for adding these music objects to the score. The palette would also include tools for selecting, moving, and otherwise manipulation music objects. Users will click on the quarter-note tool and use it to add quarter notes to the score. Or they can use the move tool to move a note up or down on the staff, thereby changing its pitch
April 18, 2023 18
Let’s assume the framework provides an abstract Graphics class for graphical components, like notes and staves. Moreover, it’ll provide an abstract Tool class for defining tools like those in the palette. The framework also predefines a GraphicTool subclass for tools that create instances of graphical objects and add them to the document
April 18, 2023 19
structurestructure
April 18, 2023 20
CollaborationsCollaborations
A client asks a prototype to clone itself
April 18, 2023 21
Command Command Object BehavioralObject Behavioral
IntentIntent
Encapsulate a request as an object,thereby letting you
parameterize clients with different requests, queue or log requests, and support undoable operations
MotivationMotivation Sometimes it’s necessary to issueSometimes it’s necessary to issue
April 18, 2023 22
StructureStructure
April 18, 2023 23
CollaborationsCollaborations-- The clients creates a ConcreteCommand ojbect and specifies -- The clients creates a ConcreteCommand ojbect and specifies
its recieverits reciever
April 18, 2023 24
Iterator Iterator Object CreationalObject Creational
IntentIntent
Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation
MotivationMotivation
List
Count()Append(Element)Remove(Element)…
ListIteratorFirst()Next()IsDone()CurrentItem()
index
list
April 18, 2023 25
StructureStructure
April 18, 2023 26
CollaborationsCollaborations
-- A ConcreteIterator keeps track of the current object in the aggregate and can compute the succeeding object in the traversal
April 18, 2023 27
MediatorMediator Object Behavioral
IntentIntent
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.
What is a MediatorWhat is a Mediator -- A mediator is responsible for controlling and coordinating
the interactions of a group of objects. The mediator serves as an intermediary that keeps objects in the group form referring to each other explicitly. The objects only know the mediator, thereby reducing the number of interconnections
April 18, 2023 28
Example
aClient director
aListBox
director
aFontDialogDirector
aButton
director
anEntryField
director
April 18, 2023 29
StructureStructure
April 18, 2023 30
CollaborationsCollaborations
Colleagues send and receive requests from a Mediator object. The mediator implements the cooperative behavior by routing requests between the appropriate colleague(s)
April 18, 2023 31
Observer Observer Object BehavioralObject Behavioral
IntentIntent
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically
ExampleExample
a b cx 60 30 10y 50 30 20z 80 10 10
1 2 3 4
x
a
x
1
2
3
4
A = 50%B= 30%C= 20%
observers
subjectChange notificationChange notification
Requests, modificationsRequests, modifications
x
y
z
a b c
60
50
80
30
30
10
10
20
10
April 18, 2023 32
StructureStructure
April 18, 2023 33
CollaborationCollaboration - ConcreteSubject notifies its observers whenever a change occurs that could make its observers’ state inconsistent with its own. - After being informed of a change in the concrete subject, a ConcreteObserver object may query the subject for information. ConcreteObserver uses this information to reconcile its state with that of the subject.
April 18, 2023 34
State State Object BehavioralObject Behavioral
IntentIntent
Allow an object to alter its behavior when its internal state changes. The Object will appear to change its class
ExampleExample
State->Open
TCPConnectionOpen()Close()Acknowledge()
TcpState
Open()Close()Acknowledge()
TCPEstablished
TCPListen TCPClosedOpen()Close()Acknowledge()
Open()Close()Acknowledge()
Open()Close()Acknowledge()
April 18, 2023 35
StructureStructure
April 18, 2023 36
CollabortionsCollabortions
- Context delegates state-specific requests to the
current ConcreteState object. - Context is the primary interface for clients. Clients can configure a context with State objects. Once a context is configured, its clients don’t have to deal with the State objects directly. - Either Context or the ConcreteState subclasses can decide which state succeeds another and under what circumstances
April 18, 2023 37
IntentIntent
Define a family of algorithms, encapsulate each one, and make them interchangeable.Strategy lets the algorithm vary independently from clients that use it
ExampleExample
Compositor->compose()
CompositionTraverse()Repair()
Compositor
compose()
compose()Compose()
compose()
SimpleComposer ArrayCompositor
StrategyStrategy object Behavioralobject Behavioral
TexCompositor
compose()
April 18, 2023 38
StructureStructure
April 18, 2023 39
CollaborationsCollaborations - Strategy and Context interact to implement the chosen
algorithm. A context may pass all data required by the algorithm to the strategy when the algorithm is called . Alternatively, the context can pass itself as an argument to Strategy operations. That lets the strategy call back on the context as required.
- A context forwards requests from its clients to its strategy. Clients usually create and pass a ConcreteStrategy object to the context; thereafter, clients interact with the context exclusively. There is often a family of ConcreteStrategy classes for a client to choose from
April 18, 2023 40
Template Method Template Method Class BehavioralClass Behavioral
IntentIntent 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.
ExampleExample
ApplicationApplication
AddDocument()openDocument()DoCreateDocument()canOpenDocument()AboutToOpenDocument
MyApplication
DoCreateDocument()canOpenDocument()AboutToOpenDocument
Document
Save()Open()Close()doRead()
MyDocument
DoRead() Return new MyDocument
docs
April 18, 2023 41
StructureStructure
April 18, 2023 42
CollaborationCollaboration
ConcreteClass relies on AbstractClass to implement the invariant steps of the algorithm
April 18, 2023 43
Visitor Visitor Object BehavioralObject Behavioral
IntentIntent
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
ExampleExample
VariableRefNode AssignmentNode
TypeCheck()GenerateCode()PrettyPrint()
TypeCheck()GenerateCode()PrettyPrint()
TypeCheck()GenerateCode()PrettyPrint()
Node
April 18, 2023 44
StructureStructure
April 18, 2023 45
CollaborationCollaboration - A client that uses the Visitor pattern must create a - A client that uses the Visitor pattern must create a
ConcreteVisitor object and then traverse the object ConcreteVisitor object and then traverse the object structure, visiting each element with the visitorstructure, visiting each element with the visitor
- When an element is visited, it calls the visitor operation - When an element is visited, it calls the visitor operation that corresponds to its class. The element supplies itself as that corresponds to its class. The element supplies itself as an argument to this operation to let the visitor access its an argument to this operation to let the visitor access its state, if necessary.state, if necessary.