SlideShare uma empresa Scribd logo
1 de 51
1
Intel Confidential
1Introduction toIntroduction to
Design PatternsDesign Patterns
and applicationand application for object oriented SW designfor object oriented SW design
Asa Ben-Tzur
WW01’2005
2
Intel Confidential
2
Presentation GoalsPresentation Goals
Introduction to design patterns concept
Introduction to using design patterns in object
oriented design
Introduction to GoF design patterns
Enable attendees to efficiently self-learn design
patterns theory and practice
Encourage design pattern usage in FETA group
Non-Goals
 SW methodology/architecture/design/etc. class
 Pattern cook-book class
 UML class
3
Intel Confidential
3
AgendaAgenda
History in a nutshell
Design pattern definitions
GoF example #1: Observer pattern
GoF example #2: Builder pattern
GoF example #3: Strategy pattern
Using Design Patterns for SW
development
Summary
4
Intel Confidential
4
Design Patterns HistoryDesign Patterns History
Christopher Alexander, a professor of
architecture at UC Berkeley, is considered
as the godfather of design pattern concept
 Concept foundation laid out in three publications:
– “Notes on the synthesis of form” – modern architecture
fails to meet human needs - 1964
– “A pattern language” – design patterns for building
architecture – 1977
– “The timeless way of building” – theory foundation - 1979
Ward Cunningham and Kent Beck brought
Alexander’s concept to SW design in 1987
 Five pattern language was used to develop a user
interface for Tektronix
5
Intel Confidential
5
Design Patterns History (cont.)Design Patterns History (cont.)
Design Patterns book published by GoF in
1994
 GoF are:
– Erich Gamma
– Richard Helm
– Ralph Johnson
– John Vlissides
 GoF book presented 23 design patterns, based on
thorough analysis of several SW systems.
– Became widely accepted and started design patterns hype
– Is widely used in OOD
– examples from FETA code will follow.
– Is the best place to start learning design patterns usage
6
Intel Confidential
6
Design Patterns History (cont.)Design Patterns History (cont.)
Design Patterns today
 Applied to multiple domains beyond SW design (e.g.
architecture, analysis, organization, …).
– Design is still the most common usage
 Multiple sources of information
– Books
– Web-sites
– Organizations
– Conferences
 No additional breakthrough in SW design
7
Intel Confidential
7
AgendaAgenda
History in a nutshell
Design pattern definitions
GoF example #1: Observer pattern
GoF example #2: Builder pattern
GoF example #3: Flyweight pattern
Using Design Patterns for SW
development
Summary
8
Intel Confidential
8
Design Pattern Definition #1Design Pattern Definition #1
Christopher Alexander:
“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.”
9
Intel Confidential
9
Design Pattern Definition #2Design Pattern Definition #2
GoF:
“A design pattern systematically names, motivates, and
explains a general design that addresses a recurring
design problem in object-oriented systems. It describes
the problem, the solution, when to apply the solution,
and its consequences. It also gives implementation hints
and examples. The solution is a general arrangement of
objects and classes that solve the problem. The solution
is customized and implemented to solve the problem in a
particular context.”
10
Intel Confidential
10
GoF pattern elementsGoF pattern elements
Pattern name
Problem
Solution
Consequences
11
Intel Confidential
11
A simple pattern exampleA simple pattern example
Name: Sleepless Talk
Problem: How to keep the audience awake
during a technical presentation.
Solution: The presentation should last no
longer then two hours. Deliver chocolate
during the presentation. Throw in some
surprises/jokes.
Consequences:
 Deep technical topics may need to be broken down to
several sessions.
 Stand-up training required for presenters 
 Audience may grow fat 
12
Intel Confidential
12
AgendaAgenda
History in a nutshell
Design pattern definitions
GoF example #1: Observer pattern
GoF example #2: Builder pattern
GoF example #3: Flyweight pattern
Using Design Patterns for SW
development
Summary
13
Intel Confidential
13
Observer Design PatternObserver Design Pattern
Intent
 Define a one-to-many dependency between objects so
that when one object changes state, all its dependents
are notified and updated automatically.
Motivation
 Decouple a system into collection of cooperating classes
while maintaining consistency between related objects.
– Avoid making the classes tightly coupled
Example
 Model-View architecture
– Windows file explorer
– Gateview root cause analysis annotation
– Seqver mapping advisor equivalence classes annotation
14
Intel Confidential
14
Observer Pattern StructureObserver Pattern Structure
cd Observer
Observer
+ «pure» update() : void
Subject
- m_observers: std::list<Observer*>
+ «pure» attach(Observer*) : void
+ «pure» detach(Observer*) : void
# notify() : void
ConcreteSubject
- m_state: int
+ getState() : void
+ setState() : void
ConcreteObserver
- m_state: double
+ update() : void
m_observers
0..*
m_subject
«realize»
15
Intel Confidential
15
Observer Pattern ParticipantsObserver Pattern Participants
Subject
 Knows it’s observers
 Provides an interface for attaching/detaching observer objects
Observer
 Defines an updating interface
Concrete Subject
 Stores state of interest to concrete observers
 Sends notification to observers when it’s state changes
Concrete Observer
 Maintains a reference to Concrete Subject object (*)
 Stores state that should stay consistent with the subject’s
 Implements the observer update interface
16
Intel Confidential
16
Observer Pattern CollaborationsObserver Pattern Collaborations
sd Observer
:ConcreteSubject :ConcreteObserver :ConcreteObserver
setState()
notify()
update()
getState()
update()
getState()
17
Intel Confidential
17
Consequences & ImplementationConsequences & Implementation
Consequences
 Abstract coupling between Subject and Observer
– Can reside in different layers of the architecture
 Support for broadcast communication
– Subject doesn’t need to know where to send the message –
all subscribed observers get the update.
 Unexpected updates
– Trivial implementation may lead to unexpected expensive
run time overhead
Implementation
 Observing multiple subjects
 Subscribing for specific update events
– “Observer with aspect”
18
Intel Confidential
18
Example: Gateview ExpandExample: Gateview Expand
cd Gateview root cause analysis
Gateview
+ attach(IExpandObserver*) : void
+ detach(IExpandObserver*) : void
# notifyOnExpand() : void
+ attach(IDestroyObserver*) : void
+ detach(IDestroyObserver*) : void
# notifyOnDestroy() : void
ExpandObserver
+ «pure» update(string, string) : void
RootCauseManager
+ update(string, string) : void
«realize»
m_expandObservers
0..*
19
Intel Confidential
19
Source Code ExamplesSource Code Examples
/vobs/gandalf/utility/design_pattern/Observer.h
/
vobs/gandalf/utility/design_pattern/ObserverWithA
spect.h
/vobs/fev_debug_idc/gateview/gateview.h
/vobs/fev_debug_idc/gateview/notification/*.h
/vobs/fev_debug_idc/gateview/RootCause*.h
20
Intel Confidential
20
AgendaAgenda
History in a nutshell
Design pattern definitions
GoF example #1: Observer pattern
GoF example #2: Builder pattern
GoF example #3: Flyweight pattern
Using Design Patterns for SW
development
Summary
21
Intel Confidential
21
Builder Design PatternBuilder Design Pattern
Intent
 Separate the construction of a complex object from its
representation so that the same construction process can
create different representations.
Motivation
 A reader for the RTF document format should be able to convert
RTF to many text formats. The solution is to configure
RTFReader class with TextConverter object that converts RTF
to other textual representation. As RTFReader parses the RTF
document, it uses TextConverter to convert tokens.
Example
 FSM export (Not Implemented)
– Model writers (exlif, Verilog, ..)
– Trace writers (VCD, CSIM, FSDB)
 Forte2 XML parser
22
Intel Confidential
22
Builder Pattern StructureBuilder Pattern Structure
cd Builder
Director
+ construct() : void
Builder
+ «pure» buildPart()
ConcreteBuilder
+ buildPart()
+ getResult() : Product*
«realize»
m_builder
23
Intel Confidential
23
Builder Pattern ParticipantsBuilder Pattern Participants
Builder
 Specifies abstract interface for creating parts of a product
object.
ConcreteBuilder
 Constructs and assembles parts of the product by
implementing the Builder interface.
 Defines and keeps track of the representation it creates.
 Provides an interface for retrieving the product.
Director
 Constructs an object using the builder interface.
Product
 Represents a complex object under construction.
 Includes classes that define the constituent parts, including
interfaces for assembling the parts into the final result.
24
Intel Confidential
24
Builder Pattern CollaborationsBuilder Pattern Collaborations
sd Builder
Client
:ConcreteBuilder
:Director
new ConcreteBuilder
new Director(ConcreteBuilder)
construct()
buildPartA()
buildPartB()
buildPartC()
Product*:= getResult()
25
Intel Confidential
25
Consequences & ImplementationConsequences & Implementation
Consequences
 Hide the product’s internal representation
 It gives you finer control over the construction process
Implementation
 Assembly and construction interface
 Empty methods as default in Builder (C++).
26
Intel Confidential
26
Example: Forte2 XML readerExample: Forte2 XML reader
cd Forte2XML
XmlReader
+ XmlReader(IXmlConverter*)
+ read(const char*) : bool
XmlConverter
+ «pure» convertElementBegin(const char*, const char**) : void
+ «pure» convertElementEnd(const char*) : void
FlXmlConverter
+ convertElementBegin(const char*, const char**) : void
+ convertElementEnd(const char*) : void
gandalf::XmlConfigurationFile
+ convertElementBegin(const char*, const char**) : void
+ convertElementEnd(const char*) : void
«realize»
builder
«realize»
27
Intel Confidential
27
Source Code ExampleSource Code Example
Source code examples
 /vobs/ldm/include/fl_xml/*.h
 /vobs/ldm/src/fl_xml/*.cpp
 /vobs/ldm/src/fl/Rtl2RtlEcoLogConverter.*
 /vobs/gandalf/utility/config/ConfigurationXmlSource.*
28
Intel Confidential
28
AgendaAgenda
History in a nutshell
Design pattern definitions
GoF example #1: Observer pattern
GoF example #2: Builder pattern
GoF example #3: Strategy pattern
Using Design Patterns for SW
development
Summary
29
Intel Confidential
29
Strategy Design PatternStrategy Design Pattern
Intent
 Define a family of algorithms, encapsulate each one, and make them
interchangeable. Strategy lets the algorithm vary independently from
clients that use it.
Motivation
 Many algorithms exist for breaking a stream of text (paragraph) into
lines. Hard-wiring all such algorithms into the classes that require them
isn’t desirable for several reasons:
– Clients that need line breaking become more complex if they include the line
breaking code. The problem grows if a client should support multiple
algorithms.
– Different line breaking algorithms will be appropriate at different times.
– It’s difficult to add new algorithms and vary existing ones when line
breaking is an integral part of the client.
 We can avoid the problem by defining classes that encapsulate different
line breaking algorithms. An encapsulated algorithm is called a strategy.
Example
 LIRA language specific type checking
 Gateview traversal algorithm
30
Intel Confidential
30
Strategy Pattern StructureStrategy Pattern Structure
cd Strategy
Context
+ contextInterface()
Strategy
+ «pure» algorithmInterface()
ConcreteStrategyA
+ algorithmInterface()
ConcreteStrategyB
+ algorithmInterface()
ConcreteStrategyC
+ algorithmInterface()
m_strategy
«realize» «realize» «realize»
31
Intel Confidential
31
Strategy Pattern ParticipantsStrategy Pattern Participants
Strategy
 Declares an interface common to all supported
algorithms. Context uses this interface to call the
algorithm defined by a ConcreteStrategy.
ConcreteStrategy
 Implements the algorithm using Strategy interface.
Context
 Is configured with a ConcreteStrategy object.
 Maintains reference to the Strategy object.
 May define an interface that lets Strategy access it’s data.
32
Intel Confidential
32
Consequences & ImplementationConsequences & Implementation
Consequences
 Families of related algorithms
 An alternative to subclassing
 Strategies eliminate conditional statements
 Choice of implementations
– Performance tradeoffs
 Potential communication overhead between Context and
Strategy
Implementation
 Set the strategy of the context via virtual interface (run
time) or template parameter (compile time).
 Pass state arguments to the strategy object, or pass the
context object itself.
 An algorithm can have a default strategy
33
Intel Confidential
33
Example: Lira Type CheckerExample: Lira Type Checker
cd Typecheck
ILanguageRules
+ IsLegalLValue(MiscStateInfo*) : bool
+ IsLegalRValue(MiscStateInfo*) : bool
+ CheckObjectDeclaration(MiscStateInfo*) : bool
IHDLLanguageRules
+ IsLegalLValue(MiscStateInfo*) : bool
+ IsLegalRValue(MiscStateInfo*) : bool
+ CheckObjectDeclaration(MiscStateInfo*) : bool
VerilogLanguageRules
+ IsLegalLValue(MiscStateInfo*) : bool
+ IsLegalRValue(MiscStateInfo*) : bool
+ CheckObjectDeclaration(MiscStateInfo*) : bool
CTypeChecker
+ CTypeChecker(ILanguageRules&)
+ TypeCheckExpression(MiscStateInfoe*) : bool
m_languageRules
«realize» «realize»
34
Intel Confidential
34
Source Code ExamplesSource Code Examples
/vobs/lira/typecheck/LanguageRules.h
/vobs/lira/typecheck/IHDLLanguageRules
/vobs/lira/typecheck/VerilogLanguageRules
/vobs/lira/utilities/CdfgDfsIterator.h
 Several concrete strategies available in the header file
35
Intel Confidential
35
AgendaAgenda
History in a nutshell
Design pattern definitions
GoF example #1: Observer pattern
GoF example #2: Builder pattern
GoF example #3: Strategy pattern
Using Design Patterns for SW
development
Summary
36
Intel Confidential
36
Using Design PatternsUsing Design Patterns
Product Definition
Requirements Gathering
Analysis
Design
Implementation
Integration & Testing
Deployment & Support
Design Patterns are applied
during the Design phase ( )
37
Intel Confidential
37
Using Design PatternsUsing Design Patterns
Design Patterns provide an abstract
“BKM” solution to recurring problems
 Problem is described
 Solution is outlined
 Implementation trade offs are explained
 Related patterns are listed
When encountering a design problem
 Scan the pattern collection for relevant patterns
 Check applicability
 Read through the gorry details
 Consider implementation trade offs
– Including applying related patterns
 Design & implement your solution
38
Intel Confidential
38
Using Design PatternsUsing Design Patterns
Good Variance
 Design Patterns are expected to be adjusted to the design
environment/problem domain of the system.
– Forming the pattern language of the development team.
 Patterns application is expected to adjust itself to the concrete
composition of forces in the concrete problem it is applied to solve.
– Avoid creating design pattern libraries
– Exception: reference implementation
– Exception: frequently reucurring concrete problem
– Exception: Idioms
Bad Variance
 Design Pattern should not vary between different application to the
same system.
– NIH syndrom
 Pattern application should not vary between different application to
“identical” environment.
– NIH syndrom
– Lack of standard
 Pattern application should be clearly distinguished in the
implementation code.
– Using comments and pattern “keywords”
39
Intel Confidential
39
GoF Patterns UsageGoF Patterns Usage
Pattern Forte2 Lira Gandalf
Abstract Factory -(*) + -
Builder + + +
Factory Method - - +
Singleton + + +
Adapter -(*) + +
Bridge - + -
Composite + + +
Flyweight - - +
Command + - +
Iterator + + +
Observer + - +
Strategy - + -
Visitor + + -
40
Intel Confidential
40
Beyond Go4 PatternsBeyond Go4 Patterns
Multiple kinds of patterns exists
 Organizational Patterns
 Architectural Patterns
– e.g. Model-View-Controller, Pipes and Filters
 Design Patterns
 Idioms (Coding Patterns or BKM)
 Many more …
Multiple sources available
 Partial list at the end of the presentation
New patterns can be added based on
developer/team experience
41
Intel Confidential
41
Alexander on Design Patterns (1/2)Alexander on Design Patterns (1/2)
But still a fundamental question of practicality must lie
at the forefront. Does all this thought, philosophy, help
people to write better programs? For the instigators of
this approach to programming too, as in architecture, I
suppose a critical question is simply this: Do the people
who write these programs, using alexandrian patterns,
or any other methods,do they do better work? Are the
programs better? Do they get better results, more
efficiently, more speedily, more profoundly? Do people
actually feel more alive when using them? Is what is
accomplished by these programs, and by the people who
run these programs and by the people who are affected
by them, better, more elevated, more insightful, better by
ordinary spiritual standards?
42
Intel Confidential
42
Alexander on Design Patterns (2/2)Alexander on Design Patterns (2/2)
In my life as an architect, I find that the single thing
which inhibits young professionals, new students most
severely, is their acceptance of standards that are too low.
If I ask a student whether her design is as good as
Chartres, she often smiles tolerantly at me as if to say, “Of
course not, that isn’t what I am trying to do. . . . I could
never do that.”
Then, I express my disagreement, and tell her: “That
standard must be our standard. If you are going to be a
builder, no other standard is worthwhile. That is what I
expect of myself in my own buildings, and it is what I
expect of my students.” Gradually, I show the students
that they have a right to ask this of themselves, and must
ask this of themselves. Once that level of standard is in
their minds, they will be able to figure out, for themselves,
how to do better, how to make something that is as
profound as that.
43
Intel Confidential
43
SummarySummary
Design Patterns are a tool to help you write
good programs
Design Patterns provide a flexible “BKM”
solution to recurring problems
Design pattern provide insight and
solution guidelines to the designer, not a
software library.
Sharing a pattern language can help a
design team to create good programs
Design Patterns are in production usage in
FETA/LVT products.
44
Intel Confidential
44
ContributorsContributors
Thanks to:
 Sergey Pimenov for explaining Gateview Observer
pattern implementation
 Yulik Feldman and Noam Farkash for providing
information on design pattern usage in LIRA and Forte2
 Detect team members for continues effort to improve our
software design skills
 Special thanks to Jacob Katz for contributing LIRA type
checker example
45
Intel Confidential
45
Where to get more informationWhere to get more information
Intel-U:
 Design Patterns (Hi-Tech)
Web sites:
 Detailed Introduction by Brad Appleton:
– http://www.cmcrossroads.com/bradapp/docs/patterns-intro.html
 Hillside group:
– http://hillside.net/
 Pattern links:
– http://www.anupriyo.com/oopfm.shtml
Books:
 Design Patterns
 Pattern-Oriented Software Architecture
 http://www.dreamsongs.com/NewFiles/PatternsOfSoftware.pdf
– Assays on Design Patterns, including introduction by Alexander.
46
Intel Confidential
46
BackupBackup
47
Intel Confidential
47
Translator Design PatternTranslator Design Pattern
Fady et. allFady et. all
Intent
 Replace the behavior of a class dynamically into another behavior while
maintaining the same interface clients expect. Translator class allows
mid-level classes to modify the behavior of lower level classes without
impacting higher level classes.
Motivation
 An application processing a large collection of data objects is
sometimes required to modify the contents of a small subset of the
objects.
 The translator pattern enables the isolation of such modification to the
modifying code. The rest of the application code (both the data objects
and processing application) remains unchanged.
Example
 Forte2 Verilog writer
– exlif to Verilog name translation.
 Gandalf waveform enumerated trace values
48
Intel Confidential
48
Translator Pattern StructureTranslator Pattern Structure
cd Translator
Item
+ «pure» getAttribute()
+ «pure» method()
ConcreteItem
+ getAttribute()
+ method()
Translator
+ getAttribute()
+ method()
return translate( item->getAttribute() );
item
«realize» «realize»
49
Intel Confidential
49
Translator Pattern ParticipantsTranslator Pattern Participants
Item
 Defines the interface for objects that may be translated
dynamically.
ConcreteItem
 Concrete implementation of Item interface.
Translator
 Implements Item interface.
 Maintains a reference to the Item being translated.
 Modifies the Item behavior.
50
Intel Confidential
50
Consequences & ImplementationConsequences & Implementation
Consequences
 Translation is hidden from data processors. Avoids distribution
special case handling to multiple data processors.
 Data processors depend on Item interface only (are
independent of Translator code).
 Translator is reused by multiple data processors, both at code
level and object level.
Implementation
 The Translator may keep a reference to the translated item or
cache the translation.
 Translator for complex items may require implementing several
translation classes (e.g. IteratorTranslator,
AttributeTranslator, ..).
 Translator for small classes (e.g. without virtual interface) may
be expensive. Consider using Flyweight pattern.
51
Intel Confidential
51
Source Code ExamplesSource Code Examples
/vobs/gandalf/sti/sti/TraceItem.h
/vobs/gandalf/sti/sti/TraceValueIterator.h
/vobs/gandalf/view/waveform/Enumerated*

Mais conteúdo relacionado

Destaque

SW development process and the leading indicator
SW development process and the leading indicatorSW development process and the leading indicator
SW development process and the leading indicatorJean Pаoli
 
Cohr managing stress training
Cohr managing stress trainingCohr managing stress training
Cohr managing stress trainingJean Pаoli
 
Effective prioritization & zbb
Effective prioritization & zbbEffective prioritization & zbb
Effective prioritization & zbbJean Pаoli
 
PMC post implementation review
PMC post implementation reviewPMC post implementation review
PMC post implementation reviewJean Pаoli
 
Diversity in thinking styles (part 1)
Diversity in thinking styles (part 1)Diversity in thinking styles (part 1)
Diversity in thinking styles (part 1)Jean Pаoli
 

Destaque (10)

08060 c foils
08060 c foils08060 c foils
08060 c foils
 
Design patterns
Design patternsDesign patterns
Design patterns
 
SW development process and the leading indicator
SW development process and the leading indicatorSW development process and the leading indicator
SW development process and the leading indicator
 
Cohr managing stress training
Cohr managing stress trainingCohr managing stress training
Cohr managing stress training
 
Effective prioritization & zbb
Effective prioritization & zbbEffective prioritization & zbb
Effective prioritization & zbb
 
PMC post implementation review
PMC post implementation reviewPMC post implementation review
PMC post implementation review
 
PMP study TTT
PMP study TTTPMP study TTT
PMP study TTT
 
Diversity in thinking styles (part 1)
Diversity in thinking styles (part 1)Diversity in thinking styles (part 1)
Diversity in thinking styles (part 1)
 
Pmp study: time
Pmp study: timePmp study: time
Pmp study: time
 
Unified process
Unified processUnified process
Unified process
 

Semelhante a Design patterns intro

Arch06 1
Arch06 1Arch06 1
Arch06 1nazn
 
Building modular software with OSGi - Ulf Fildebrandt
Building modular software with OSGi - Ulf FildebrandtBuilding modular software with OSGi - Ulf Fildebrandt
Building modular software with OSGi - Ulf Fildebrandtmfrancis
 
Sofwear deasign and need of design pattern
Sofwear deasign and need of design patternSofwear deasign and need of design pattern
Sofwear deasign and need of design patternchetankane
 
Simon Brown: Software Architecture as Code at I T.A.K.E. Unconference 2015
Simon Brown: Software Architecture as Code at I T.A.K.E. Unconference 2015Simon Brown: Software Architecture as Code at I T.A.K.E. Unconference 2015
Simon Brown: Software Architecture as Code at I T.A.K.E. Unconference 2015Mozaic Works
 
Efficient Code Organisation
Efficient Code OrganisationEfficient Code Organisation
Efficient Code OrganisationSqueed
 
An Introduction To Model  View  Controller In XPages
An Introduction To Model  View  Controller In XPagesAn Introduction To Model  View  Controller In XPages
An Introduction To Model  View  Controller In XPagesUlrich Krause
 
02 architectures in_context
02 architectures in_context02 architectures in_context
02 architectures in_contextMajong DevJfu
 
ITEA2-ModelWriter Project
ITEA2-ModelWriter ProjectITEA2-ModelWriter Project
ITEA2-ModelWriter ProjectFerhat Erata
 
MWLUG 2015 - An Introduction to MVC
MWLUG 2015 - An Introduction to MVCMWLUG 2015 - An Introduction to MVC
MWLUG 2015 - An Introduction to MVCUlrich Krause
 
Software Architecture Views and Viewpoints
Software Architecture Views and ViewpointsSoftware Architecture Views and Viewpoints
Software Architecture Views and ViewpointsHenry Muccini
 
ModelWriter Presentation International 01-07-2015
ModelWriter Presentation International 01-07-2015ModelWriter Presentation International 01-07-2015
ModelWriter Presentation International 01-07-2015Ferhat Erata
 
Software Patterns
Software PatternsSoftware Patterns
Software Patternskim.mens
 
torque - Automation Testing Tool for C-C++ on Linux
torque -  Automation Testing Tool for C-C++ on Linuxtorque -  Automation Testing Tool for C-C++ on Linux
torque - Automation Testing Tool for C-C++ on LinuxJITENDRA LENKA
 
Cs 1023 lec 3 architecture (week 1)
Cs 1023 lec 3 architecture (week 1)Cs 1023 lec 3 architecture (week 1)
Cs 1023 lec 3 architecture (week 1)stanbridge
 
Cs 1023 lec 3 architecture (week 1)
Cs 1023 lec 3 architecture (week 1)Cs 1023 lec 3 architecture (week 1)
Cs 1023 lec 3 architecture (week 1)stanbridge
 
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...Maarten Balliauw
 
01 intro to programming in .net
01   intro to programming in .net01   intro to programming in .net
01 intro to programming in .netFelisha Hosein
 

Semelhante a Design patterns intro (20)

Arch06 1
Arch06 1Arch06 1
Arch06 1
 
Building modular software with OSGi - Ulf Fildebrandt
Building modular software with OSGi - Ulf FildebrandtBuilding modular software with OSGi - Ulf Fildebrandt
Building modular software with OSGi - Ulf Fildebrandt
 
Testing method pptx
Testing method pptxTesting method pptx
Testing method pptx
 
Sofwear deasign and need of design pattern
Sofwear deasign and need of design patternSofwear deasign and need of design pattern
Sofwear deasign and need of design pattern
 
Simon Brown: Software Architecture as Code at I T.A.K.E. Unconference 2015
Simon Brown: Software Architecture as Code at I T.A.K.E. Unconference 2015Simon Brown: Software Architecture as Code at I T.A.K.E. Unconference 2015
Simon Brown: Software Architecture as Code at I T.A.K.E. Unconference 2015
 
Efficient Code Organisation
Efficient Code OrganisationEfficient Code Organisation
Efficient Code Organisation
 
An Introduction To Model  View  Controller In XPages
An Introduction To Model  View  Controller In XPagesAn Introduction To Model  View  Controller In XPages
An Introduction To Model  View  Controller In XPages
 
02 architectures in_context
02 architectures in_context02 architectures in_context
02 architectures in_context
 
ITEA2-ModelWriter Project
ITEA2-ModelWriter ProjectITEA2-ModelWriter Project
ITEA2-ModelWriter Project
 
Design patterns
Design patternsDesign patterns
Design patterns
 
MWLUG 2015 - An Introduction to MVC
MWLUG 2015 - An Introduction to MVCMWLUG 2015 - An Introduction to MVC
MWLUG 2015 - An Introduction to MVC
 
Software Architecture Views and Viewpoints
Software Architecture Views and ViewpointsSoftware Architecture Views and Viewpoints
Software Architecture Views and Viewpoints
 
ModelWriter Presentation International 01-07-2015
ModelWriter Presentation International 01-07-2015ModelWriter Presentation International 01-07-2015
ModelWriter Presentation International 01-07-2015
 
Software Patterns
Software PatternsSoftware Patterns
Software Patterns
 
torque - Automation Testing Tool for C-C++ on Linux
torque -  Automation Testing Tool for C-C++ on Linuxtorque -  Automation Testing Tool for C-C++ on Linux
torque - Automation Testing Tool for C-C++ on Linux
 
Dot net introduction
Dot net introductionDot net introduction
Dot net introduction
 
Cs 1023 lec 3 architecture (week 1)
Cs 1023 lec 3 architecture (week 1)Cs 1023 lec 3 architecture (week 1)
Cs 1023 lec 3 architecture (week 1)
 
Cs 1023 lec 3 architecture (week 1)
Cs 1023 lec 3 architecture (week 1)Cs 1023 lec 3 architecture (week 1)
Cs 1023 lec 3 architecture (week 1)
 
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
ConFoo Montreal - Microservices for building an IDE - The innards of JetBrain...
 
01 intro to programming in .net
01   intro to programming in .net01   intro to programming in .net
01 intro to programming in .net
 

Último

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 

Último (20)

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

Design patterns intro

  • 1. 1 Intel Confidential 1Introduction toIntroduction to Design PatternsDesign Patterns and applicationand application for object oriented SW designfor object oriented SW design Asa Ben-Tzur WW01’2005
  • 2. 2 Intel Confidential 2 Presentation GoalsPresentation Goals Introduction to design patterns concept Introduction to using design patterns in object oriented design Introduction to GoF design patterns Enable attendees to efficiently self-learn design patterns theory and practice Encourage design pattern usage in FETA group Non-Goals  SW methodology/architecture/design/etc. class  Pattern cook-book class  UML class
  • 3. 3 Intel Confidential 3 AgendaAgenda History in a nutshell Design pattern definitions GoF example #1: Observer pattern GoF example #2: Builder pattern GoF example #3: Strategy pattern Using Design Patterns for SW development Summary
  • 4. 4 Intel Confidential 4 Design Patterns HistoryDesign Patterns History Christopher Alexander, a professor of architecture at UC Berkeley, is considered as the godfather of design pattern concept  Concept foundation laid out in three publications: – “Notes on the synthesis of form” – modern architecture fails to meet human needs - 1964 – “A pattern language” – design patterns for building architecture – 1977 – “The timeless way of building” – theory foundation - 1979 Ward Cunningham and Kent Beck brought Alexander’s concept to SW design in 1987  Five pattern language was used to develop a user interface for Tektronix
  • 5. 5 Intel Confidential 5 Design Patterns History (cont.)Design Patterns History (cont.) Design Patterns book published by GoF in 1994  GoF are: – Erich Gamma – Richard Helm – Ralph Johnson – John Vlissides  GoF book presented 23 design patterns, based on thorough analysis of several SW systems. – Became widely accepted and started design patterns hype – Is widely used in OOD – examples from FETA code will follow. – Is the best place to start learning design patterns usage
  • 6. 6 Intel Confidential 6 Design Patterns History (cont.)Design Patterns History (cont.) Design Patterns today  Applied to multiple domains beyond SW design (e.g. architecture, analysis, organization, …). – Design is still the most common usage  Multiple sources of information – Books – Web-sites – Organizations – Conferences  No additional breakthrough in SW design
  • 7. 7 Intel Confidential 7 AgendaAgenda History in a nutshell Design pattern definitions GoF example #1: Observer pattern GoF example #2: Builder pattern GoF example #3: Flyweight pattern Using Design Patterns for SW development Summary
  • 8. 8 Intel Confidential 8 Design Pattern Definition #1Design Pattern Definition #1 Christopher Alexander: “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.”
  • 9. 9 Intel Confidential 9 Design Pattern Definition #2Design Pattern Definition #2 GoF: “A design pattern systematically names, motivates, and explains a general design that addresses a recurring design problem in object-oriented systems. It describes the problem, the solution, when to apply the solution, and its consequences. It also gives implementation hints and examples. The solution is a general arrangement of objects and classes that solve the problem. The solution is customized and implemented to solve the problem in a particular context.”
  • 10. 10 Intel Confidential 10 GoF pattern elementsGoF pattern elements Pattern name Problem Solution Consequences
  • 11. 11 Intel Confidential 11 A simple pattern exampleA simple pattern example Name: Sleepless Talk Problem: How to keep the audience awake during a technical presentation. Solution: The presentation should last no longer then two hours. Deliver chocolate during the presentation. Throw in some surprises/jokes. Consequences:  Deep technical topics may need to be broken down to several sessions.  Stand-up training required for presenters   Audience may grow fat 
  • 12. 12 Intel Confidential 12 AgendaAgenda History in a nutshell Design pattern definitions GoF example #1: Observer pattern GoF example #2: Builder pattern GoF example #3: Flyweight pattern Using Design Patterns for SW development Summary
  • 13. 13 Intel Confidential 13 Observer Design PatternObserver Design Pattern Intent  Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. Motivation  Decouple a system into collection of cooperating classes while maintaining consistency between related objects. – Avoid making the classes tightly coupled Example  Model-View architecture – Windows file explorer – Gateview root cause analysis annotation – Seqver mapping advisor equivalence classes annotation
  • 14. 14 Intel Confidential 14 Observer Pattern StructureObserver Pattern Structure cd Observer Observer + «pure» update() : void Subject - m_observers: std::list<Observer*> + «pure» attach(Observer*) : void + «pure» detach(Observer*) : void # notify() : void ConcreteSubject - m_state: int + getState() : void + setState() : void ConcreteObserver - m_state: double + update() : void m_observers 0..* m_subject «realize»
  • 15. 15 Intel Confidential 15 Observer Pattern ParticipantsObserver Pattern Participants Subject  Knows it’s observers  Provides an interface for attaching/detaching observer objects Observer  Defines an updating interface Concrete Subject  Stores state of interest to concrete observers  Sends notification to observers when it’s state changes Concrete Observer  Maintains a reference to Concrete Subject object (*)  Stores state that should stay consistent with the subject’s  Implements the observer update interface
  • 16. 16 Intel Confidential 16 Observer Pattern CollaborationsObserver Pattern Collaborations sd Observer :ConcreteSubject :ConcreteObserver :ConcreteObserver setState() notify() update() getState() update() getState()
  • 17. 17 Intel Confidential 17 Consequences & ImplementationConsequences & Implementation Consequences  Abstract coupling between Subject and Observer – Can reside in different layers of the architecture  Support for broadcast communication – Subject doesn’t need to know where to send the message – all subscribed observers get the update.  Unexpected updates – Trivial implementation may lead to unexpected expensive run time overhead Implementation  Observing multiple subjects  Subscribing for specific update events – “Observer with aspect”
  • 18. 18 Intel Confidential 18 Example: Gateview ExpandExample: Gateview Expand cd Gateview root cause analysis Gateview + attach(IExpandObserver*) : void + detach(IExpandObserver*) : void # notifyOnExpand() : void + attach(IDestroyObserver*) : void + detach(IDestroyObserver*) : void # notifyOnDestroy() : void ExpandObserver + «pure» update(string, string) : void RootCauseManager + update(string, string) : void «realize» m_expandObservers 0..*
  • 19. 19 Intel Confidential 19 Source Code ExamplesSource Code Examples /vobs/gandalf/utility/design_pattern/Observer.h / vobs/gandalf/utility/design_pattern/ObserverWithA spect.h /vobs/fev_debug_idc/gateview/gateview.h /vobs/fev_debug_idc/gateview/notification/*.h /vobs/fev_debug_idc/gateview/RootCause*.h
  • 20. 20 Intel Confidential 20 AgendaAgenda History in a nutshell Design pattern definitions GoF example #1: Observer pattern GoF example #2: Builder pattern GoF example #3: Flyweight pattern Using Design Patterns for SW development Summary
  • 21. 21 Intel Confidential 21 Builder Design PatternBuilder Design Pattern Intent  Separate the construction of a complex object from its representation so that the same construction process can create different representations. Motivation  A reader for the RTF document format should be able to convert RTF to many text formats. The solution is to configure RTFReader class with TextConverter object that converts RTF to other textual representation. As RTFReader parses the RTF document, it uses TextConverter to convert tokens. Example  FSM export (Not Implemented) – Model writers (exlif, Verilog, ..) – Trace writers (VCD, CSIM, FSDB)  Forte2 XML parser
  • 22. 22 Intel Confidential 22 Builder Pattern StructureBuilder Pattern Structure cd Builder Director + construct() : void Builder + «pure» buildPart() ConcreteBuilder + buildPart() + getResult() : Product* «realize» m_builder
  • 23. 23 Intel Confidential 23 Builder Pattern ParticipantsBuilder Pattern Participants Builder  Specifies abstract interface for creating parts of a product object. ConcreteBuilder  Constructs and assembles parts of the product by implementing the Builder interface.  Defines and keeps track of the representation it creates.  Provides an interface for retrieving the product. Director  Constructs an object using the builder interface. Product  Represents a complex object under construction.  Includes classes that define the constituent parts, including interfaces for assembling the parts into the final result.
  • 24. 24 Intel Confidential 24 Builder Pattern CollaborationsBuilder Pattern Collaborations sd Builder Client :ConcreteBuilder :Director new ConcreteBuilder new Director(ConcreteBuilder) construct() buildPartA() buildPartB() buildPartC() Product*:= getResult()
  • 25. 25 Intel Confidential 25 Consequences & ImplementationConsequences & Implementation Consequences  Hide the product’s internal representation  It gives you finer control over the construction process Implementation  Assembly and construction interface  Empty methods as default in Builder (C++).
  • 26. 26 Intel Confidential 26 Example: Forte2 XML readerExample: Forte2 XML reader cd Forte2XML XmlReader + XmlReader(IXmlConverter*) + read(const char*) : bool XmlConverter + «pure» convertElementBegin(const char*, const char**) : void + «pure» convertElementEnd(const char*) : void FlXmlConverter + convertElementBegin(const char*, const char**) : void + convertElementEnd(const char*) : void gandalf::XmlConfigurationFile + convertElementBegin(const char*, const char**) : void + convertElementEnd(const char*) : void «realize» builder «realize»
  • 27. 27 Intel Confidential 27 Source Code ExampleSource Code Example Source code examples  /vobs/ldm/include/fl_xml/*.h  /vobs/ldm/src/fl_xml/*.cpp  /vobs/ldm/src/fl/Rtl2RtlEcoLogConverter.*  /vobs/gandalf/utility/config/ConfigurationXmlSource.*
  • 28. 28 Intel Confidential 28 AgendaAgenda History in a nutshell Design pattern definitions GoF example #1: Observer pattern GoF example #2: Builder pattern GoF example #3: Strategy pattern Using Design Patterns for SW development Summary
  • 29. 29 Intel Confidential 29 Strategy Design PatternStrategy Design Pattern Intent  Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Motivation  Many algorithms exist for breaking a stream of text (paragraph) into lines. Hard-wiring all such algorithms into the classes that require them isn’t desirable for several reasons: – Clients that need line breaking become more complex if they include the line breaking code. The problem grows if a client should support multiple algorithms. – Different line breaking algorithms will be appropriate at different times. – It’s difficult to add new algorithms and vary existing ones when line breaking is an integral part of the client.  We can avoid the problem by defining classes that encapsulate different line breaking algorithms. An encapsulated algorithm is called a strategy. Example  LIRA language specific type checking  Gateview traversal algorithm
  • 30. 30 Intel Confidential 30 Strategy Pattern StructureStrategy Pattern Structure cd Strategy Context + contextInterface() Strategy + «pure» algorithmInterface() ConcreteStrategyA + algorithmInterface() ConcreteStrategyB + algorithmInterface() ConcreteStrategyC + algorithmInterface() m_strategy «realize» «realize» «realize»
  • 31. 31 Intel Confidential 31 Strategy Pattern ParticipantsStrategy Pattern Participants Strategy  Declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy. ConcreteStrategy  Implements the algorithm using Strategy interface. Context  Is configured with a ConcreteStrategy object.  Maintains reference to the Strategy object.  May define an interface that lets Strategy access it’s data.
  • 32. 32 Intel Confidential 32 Consequences & ImplementationConsequences & Implementation Consequences  Families of related algorithms  An alternative to subclassing  Strategies eliminate conditional statements  Choice of implementations – Performance tradeoffs  Potential communication overhead between Context and Strategy Implementation  Set the strategy of the context via virtual interface (run time) or template parameter (compile time).  Pass state arguments to the strategy object, or pass the context object itself.  An algorithm can have a default strategy
  • 33. 33 Intel Confidential 33 Example: Lira Type CheckerExample: Lira Type Checker cd Typecheck ILanguageRules + IsLegalLValue(MiscStateInfo*) : bool + IsLegalRValue(MiscStateInfo*) : bool + CheckObjectDeclaration(MiscStateInfo*) : bool IHDLLanguageRules + IsLegalLValue(MiscStateInfo*) : bool + IsLegalRValue(MiscStateInfo*) : bool + CheckObjectDeclaration(MiscStateInfo*) : bool VerilogLanguageRules + IsLegalLValue(MiscStateInfo*) : bool + IsLegalRValue(MiscStateInfo*) : bool + CheckObjectDeclaration(MiscStateInfo*) : bool CTypeChecker + CTypeChecker(ILanguageRules&) + TypeCheckExpression(MiscStateInfoe*) : bool m_languageRules «realize» «realize»
  • 34. 34 Intel Confidential 34 Source Code ExamplesSource Code Examples /vobs/lira/typecheck/LanguageRules.h /vobs/lira/typecheck/IHDLLanguageRules /vobs/lira/typecheck/VerilogLanguageRules /vobs/lira/utilities/CdfgDfsIterator.h  Several concrete strategies available in the header file
  • 35. 35 Intel Confidential 35 AgendaAgenda History in a nutshell Design pattern definitions GoF example #1: Observer pattern GoF example #2: Builder pattern GoF example #3: Strategy pattern Using Design Patterns for SW development Summary
  • 36. 36 Intel Confidential 36 Using Design PatternsUsing Design Patterns Product Definition Requirements Gathering Analysis Design Implementation Integration & Testing Deployment & Support Design Patterns are applied during the Design phase ( )
  • 37. 37 Intel Confidential 37 Using Design PatternsUsing Design Patterns Design Patterns provide an abstract “BKM” solution to recurring problems  Problem is described  Solution is outlined  Implementation trade offs are explained  Related patterns are listed When encountering a design problem  Scan the pattern collection for relevant patterns  Check applicability  Read through the gorry details  Consider implementation trade offs – Including applying related patterns  Design & implement your solution
  • 38. 38 Intel Confidential 38 Using Design PatternsUsing Design Patterns Good Variance  Design Patterns are expected to be adjusted to the design environment/problem domain of the system. – Forming the pattern language of the development team.  Patterns application is expected to adjust itself to the concrete composition of forces in the concrete problem it is applied to solve. – Avoid creating design pattern libraries – Exception: reference implementation – Exception: frequently reucurring concrete problem – Exception: Idioms Bad Variance  Design Pattern should not vary between different application to the same system. – NIH syndrom  Pattern application should not vary between different application to “identical” environment. – NIH syndrom – Lack of standard  Pattern application should be clearly distinguished in the implementation code. – Using comments and pattern “keywords”
  • 39. 39 Intel Confidential 39 GoF Patterns UsageGoF Patterns Usage Pattern Forte2 Lira Gandalf Abstract Factory -(*) + - Builder + + + Factory Method - - + Singleton + + + Adapter -(*) + + Bridge - + - Composite + + + Flyweight - - + Command + - + Iterator + + + Observer + - + Strategy - + - Visitor + + -
  • 40. 40 Intel Confidential 40 Beyond Go4 PatternsBeyond Go4 Patterns Multiple kinds of patterns exists  Organizational Patterns  Architectural Patterns – e.g. Model-View-Controller, Pipes and Filters  Design Patterns  Idioms (Coding Patterns or BKM)  Many more … Multiple sources available  Partial list at the end of the presentation New patterns can be added based on developer/team experience
  • 41. 41 Intel Confidential 41 Alexander on Design Patterns (1/2)Alexander on Design Patterns (1/2) But still a fundamental question of practicality must lie at the forefront. Does all this thought, philosophy, help people to write better programs? For the instigators of this approach to programming too, as in architecture, I suppose a critical question is simply this: Do the people who write these programs, using alexandrian patterns, or any other methods,do they do better work? Are the programs better? Do they get better results, more efficiently, more speedily, more profoundly? Do people actually feel more alive when using them? Is what is accomplished by these programs, and by the people who run these programs and by the people who are affected by them, better, more elevated, more insightful, better by ordinary spiritual standards?
  • 42. 42 Intel Confidential 42 Alexander on Design Patterns (2/2)Alexander on Design Patterns (2/2) In my life as an architect, I find that the single thing which inhibits young professionals, new students most severely, is their acceptance of standards that are too low. If I ask a student whether her design is as good as Chartres, she often smiles tolerantly at me as if to say, “Of course not, that isn’t what I am trying to do. . . . I could never do that.” Then, I express my disagreement, and tell her: “That standard must be our standard. If you are going to be a builder, no other standard is worthwhile. That is what I expect of myself in my own buildings, and it is what I expect of my students.” Gradually, I show the students that they have a right to ask this of themselves, and must ask this of themselves. Once that level of standard is in their minds, they will be able to figure out, for themselves, how to do better, how to make something that is as profound as that.
  • 43. 43 Intel Confidential 43 SummarySummary Design Patterns are a tool to help you write good programs Design Patterns provide a flexible “BKM” solution to recurring problems Design pattern provide insight and solution guidelines to the designer, not a software library. Sharing a pattern language can help a design team to create good programs Design Patterns are in production usage in FETA/LVT products.
  • 44. 44 Intel Confidential 44 ContributorsContributors Thanks to:  Sergey Pimenov for explaining Gateview Observer pattern implementation  Yulik Feldman and Noam Farkash for providing information on design pattern usage in LIRA and Forte2  Detect team members for continues effort to improve our software design skills  Special thanks to Jacob Katz for contributing LIRA type checker example
  • 45. 45 Intel Confidential 45 Where to get more informationWhere to get more information Intel-U:  Design Patterns (Hi-Tech) Web sites:  Detailed Introduction by Brad Appleton: – http://www.cmcrossroads.com/bradapp/docs/patterns-intro.html  Hillside group: – http://hillside.net/  Pattern links: – http://www.anupriyo.com/oopfm.shtml Books:  Design Patterns  Pattern-Oriented Software Architecture  http://www.dreamsongs.com/NewFiles/PatternsOfSoftware.pdf – Assays on Design Patterns, including introduction by Alexander.
  • 47. 47 Intel Confidential 47 Translator Design PatternTranslator Design Pattern Fady et. allFady et. all Intent  Replace the behavior of a class dynamically into another behavior while maintaining the same interface clients expect. Translator class allows mid-level classes to modify the behavior of lower level classes without impacting higher level classes. Motivation  An application processing a large collection of data objects is sometimes required to modify the contents of a small subset of the objects.  The translator pattern enables the isolation of such modification to the modifying code. The rest of the application code (both the data objects and processing application) remains unchanged. Example  Forte2 Verilog writer – exlif to Verilog name translation.  Gandalf waveform enumerated trace values
  • 48. 48 Intel Confidential 48 Translator Pattern StructureTranslator Pattern Structure cd Translator Item + «pure» getAttribute() + «pure» method() ConcreteItem + getAttribute() + method() Translator + getAttribute() + method() return translate( item->getAttribute() ); item «realize» «realize»
  • 49. 49 Intel Confidential 49 Translator Pattern ParticipantsTranslator Pattern Participants Item  Defines the interface for objects that may be translated dynamically. ConcreteItem  Concrete implementation of Item interface. Translator  Implements Item interface.  Maintains a reference to the Item being translated.  Modifies the Item behavior.
  • 50. 50 Intel Confidential 50 Consequences & ImplementationConsequences & Implementation Consequences  Translation is hidden from data processors. Avoids distribution special case handling to multiple data processors.  Data processors depend on Item interface only (are independent of Translator code).  Translator is reused by multiple data processors, both at code level and object level. Implementation  The Translator may keep a reference to the translated item or cache the translation.  Translator for complex items may require implementing several translation classes (e.g. IteratorTranslator, AttributeTranslator, ..).  Translator for small classes (e.g. without virtual interface) may be expensive. Consider using Flyweight pattern.
  • 51. 51 Intel Confidential 51 Source Code ExamplesSource Code Examples /vobs/gandalf/sti/sti/TraceItem.h /vobs/gandalf/sti/sti/TraceValueIterator.h /vobs/gandalf/view/waveform/Enumerated*