View
478
Download
1
Category
Preview:
Citation preview
11
Intel Confidential
1Introduction toIntroduction toDesign PatternsDesign Patterns
and applicationand application for object oriented SW designfor object oriented SW design
Asa Ben-Tzur
WW01’2005
22
Intel Confidential
2
Presentation GoalsPresentation GoalsIntroduction to design patterns conceptIntroduction to using design patterns in object
oriented designIntroduction to GoF design patternsEnable attendees to efficiently self-learn design
patterns theory and practiceEncourage design pattern usage in FETA group
Non-Goals SW methodology/architecture/design/etc. class Pattern cook-book class UML class
33
Intel Confidential
3
AgendaAgenda
History in a nutshellDesign pattern definitionsGoF example #1: Observer patternGoF example #2: Builder patternGoF example #3: Strategy patternUsing Design Patterns for SW
developmentSummary
44
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
55
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
66
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
77
Intel Confidential
7
AgendaAgenda
History in a nutshellDesign pattern definitionsGoF example #1: Observer patternGoF example #2: Builder patternGoF example #3: Flyweight patternUsing Design Patterns for SW
developmentSummary
88
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.”
99
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.”
1010
Intel Confidential
10
GoF pattern elementsGoF pattern elements
Pattern nameProblemSolutionConsequences
1111
Intel Confidential
11
A simple pattern exampleA simple pattern exampleName: Sleepless TalkProblem: 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
1212
Intel Confidential
12
AgendaAgenda
History in a nutshellDesign pattern definitionsGoF example #1: Observer patternGoF example #2: Builder patternGoF example #3: Flyweight patternUsing Design Patterns for SW
developmentSummary
1313
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
1414
Intel Confidential
14
Observer Pattern StructureObserver Pattern Structure
cd Observ er
Observer
+ «pure» update() : void
Subject
- m_observers: std::l ist<Observer*>
+ «pure» attach(Observer*) : void+ «pure» detach(Observer*) : void# notify() : void
ConcreteSubject
- m_state: int
+ getState() : void+ setState() : void
ConcreteObserv er
- m_state: double
+ update() : void
m_observers
0..*
m_subject
«realize»
1515
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
1616
Intel Confidential
16
Observer Pattern CollaborationsObserver Pattern Collaborations
sd Observer
:ConcreteSubject :ConcreteObserv er :ConcreteObserv er
setState()
notify()
update()
getState()
update()
getState()
1717
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”
1818
Intel Confidential
18
Example: Gateview ExpandExample: Gateview Expand
cd Gatev iew root cause analysis
Gatev iew
+ 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..*
1919
Intel Confidential
19
Source Code ExamplesSource Code Examples/vobs/gandalf/utility/design_pattern/Observer.h/vobs/gandalf/utility/design_pattern/
ObserverWithAspect.h/vobs/fev_debug_idc/gateview/gateview.h/vobs/fev_debug_idc/gateview/notification/*.h/vobs/fev_debug_idc/gateview/RootCause*.h
2020
Intel Confidential
20
AgendaAgenda
History in a nutshellDesign pattern definitionsGoF example #1: Observer patternGoF example #2: Builder patternGoF example #3: Flyweight patternUsing Design Patterns for SW
developmentSummary
2121
Intel Confidential
21
Builder Design PatternBuilder Design PatternIntent
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
2222
Intel Confidential
22
Builder Pattern StructureBuilder Pattern Structure
cd Builder
Director
+ construct() : void
Builder
+ «pure» buildPart()
ConcreteBuilder
+ buildPart()+ getResult() : Product*
«realize»
m_builder
2323
Intel Confidential
23
Builder Pattern ParticipantsBuilder Pattern ParticipantsBuilder
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.
2424
Intel Confidential
24
Builder Pattern CollaborationsBuilder Pattern Collaborations
sd Builder
Client
:ConcreteBuilder
:Director
new ConcreteBuilder
new Director(ConcreteBuilder)
construct()
buildPartA()
buildPartB()
buildPartC()
Product*:= getResult()
2525
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++).
2626
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
FlXmlConv erter
+ 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»
2727
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.*
2828
Intel Confidential
28
AgendaAgenda
History in a nutshellDesign pattern definitionsGoF example #1: Observer patternGoF example #2: Builder patternGoF example #3: Strategy patternUsing Design Patterns for SW
developmentSummary
2929
Intel Confidential
29
Strategy Design PatternStrategy Design PatternIntent
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
3030
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»
3131
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.
3232
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
3333
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»
3434
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
3535
Intel Confidential
35
AgendaAgenda
History in a nutshellDesign pattern definitionsGoF example #1: Observer patternGoF example #2: Builder patternGoF example #3: Strategy patternUsing Design Patterns for SW
developmentSummary
3636
Intel Confidential
36
Using Design PatternsUsing Design Patterns
Product DefinitionRequirements GatheringAnalysisDesignImplementationIntegration & TestingDeployment & Support
Design Patterns are applied during the Design phase ( )
3737
Intel Confidential
37
Using Design PatternsUsing Design PatternsDesign 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
3838
Intel Confidential
38
Using Design PatternsUsing Design PatternsGood 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”
3939
Intel Confidential
39
GoF Patterns UsageGoF Patterns UsagePattern Forte2 Lira GandalfAbstract Factory -(*) + -
Builder + + +
Factory Method - - +
Singleton + + +
Adapter -(*) + +
Bridge - + -
Composite + + +
Flyweight - - +
Command + - +
Iterator + + +
Observer + - +
Strategy - + -
Visitor + + -
4040
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
4141
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?
4242
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.
4343
Intel Confidential
43
SummarySummaryDesign Patterns are a tool to help you
write good programsDesign Patterns provide a flexible “BKM”
solution to recurring problemsDesign 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.
4444
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
4545
Intel Confidential
45
Where to get more informationWhere to get more informationIntel-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.
4646
Intel Confidential
46
BackupBackup
4747
Intel Confidential
47
Translator Design PatternTranslator Design PatternFady 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
4848
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»
4949
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.
5050
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.
5151
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*
Recommended