2Intel Confidential2Presentation GoalsPresentation GoalsIntroduction to design patterns conceptIntroduction to using design patterns in objectoriented designIntroduction to GoF design patternsEnable attendees to efficiently self-learn designpatterns theory and practiceEncourage design pattern usage in FETA groupNon-Goals SW methodology/architecture/design/etc. class Pattern cook-book class UML class
3Intel Confidential3AgendaAgendaHistory in a nutshellDesign pattern definitionsGoF example #1: Observer patternGoF example #2: Builder patternGoF example #3: Strategy patternUsing Design Patterns for SWdevelopmentSummary
4Intel Confidential4Design Patterns HistoryDesign Patterns HistoryChristopher Alexander, a professor ofarchitecture at UC Berkeley, is consideredas the godfather of design pattern concept Concept foundation laid out in three publications:– “Notes on the synthesis of form” – modern architecturefails to meet human needs - 1964– “A pattern language” – design patterns for buildingarchitecture – 1977– “The timeless way of building” – theory foundation - 1979Ward Cunningham and Kent Beck broughtAlexander’s concept to SW design in 1987 Five pattern language was used to develop a userinterface for Tektronix
5Intel Confidential5Design Patterns History (cont.)Design Patterns History (cont.)Design Patterns book published by GoF in1994 GoF are:– Erich Gamma– Richard Helm– Ralph Johnson– John Vlissides GoF book presented 23 design patterns, based onthorough 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
6Intel Confidential6Design 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
7Intel Confidential7AgendaAgendaHistory in a nutshellDesign pattern definitionsGoF example #1: Observer patternGoF example #2: Builder patternGoF example #3: Flyweight patternUsing Design Patterns for SWdevelopmentSummary
8Intel Confidential8Design Pattern Definition #1Design Pattern Definition #1Christopher Alexander:“Each pattern describes a problem whichoccurs over and over again in our environment,and then describes the core of the solution tothat problem, in such a way that you can usethis solution a million times over, without everdoing it the same way twice.”
9Intel Confidential9Design Pattern Definition #2Design Pattern Definition #2GoF:“A design pattern systematically names, motivates, andexplains a general design that addresses a recurringdesign problem in object-oriented systems. It describesthe problem, the solution, when to apply the solution,and its consequences. It also gives implementation hintsand examples. The solution is a general arrangement ofobjects and classes that solve the problem. The solutionis customized and implemented to solve the problem in aparticular context.”
11Intel Confidential11A simple pattern exampleA simple pattern exampleName: Sleepless TalkProblem: How to keep the audience awakeduring a technical presentation.Solution: The presentation should last nolonger then two hours. Deliver chocolateduring the presentation. Throw in somesurprises/jokes.Consequences: Deep technical topics may need to be broken down toseveral sessions. Stand-up training required for presenters Audience may grow fat
12Intel Confidential12AgendaAgendaHistory in a nutshellDesign pattern definitionsGoF example #1: Observer patternGoF example #2: Builder patternGoF example #3: Flyweight patternUsing Design Patterns for SWdevelopmentSummary
13Intel Confidential13Observer Design PatternObserver Design PatternIntent Define a one-to-many dependency between objects sothat when one object changes state, all its dependentsare notified and updated automatically.Motivation Decouple a system into collection of cooperating classeswhile maintaining consistency between related objects.– Avoid making the classes tightly coupledExample Model-View architecture– Windows file explorer– Gateview root cause analysis annotation– Seqver mapping advisor equivalence classes annotation
15Intel Confidential15Observer Pattern ParticipantsObserver Pattern ParticipantsSubject Knows it’s observers Provides an interface for attaching/detaching observer objectsObserver Defines an updating interfaceConcrete Subject Stores state of interest to concrete observers Sends notification to observers when it’s state changesConcrete Observer Maintains a reference to Concrete Subject object (*) Stores state that should stay consistent with the subject’s Implements the observer update interface
17Intel Confidential17Consequences & ImplementationConsequences & ImplementationConsequences 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 expensiverun time overheadImplementation Observing multiple subjects Subscribing for specific update events– “Observer with aspect”
20Intel Confidential20AgendaAgendaHistory in a nutshellDesign pattern definitionsGoF example #1: Observer patternGoF example #2: Builder patternGoF example #3: Flyweight patternUsing Design Patterns for SWdevelopmentSummary
21Intel Confidential21Builder Design PatternBuilder Design PatternIntent Separate the construction of a complex object from itsrepresentation so that the same construction process cancreate different representations.Motivation A reader for the RTF document format should be able to convertRTF to many text formats. The solution is to configureRTFReader class with TextConverter object that converts RTFto other textual representation. As RTFReader parses the RTFdocument, it uses TextConverter to convert tokens.Example FSM export (Not Implemented)– Model writers (exlif, Verilog, ..)– Trace writers (VCD, CSIM, FSDB) Forte2 XML parser
23Intel Confidential23Builder Pattern ParticipantsBuilder Pattern ParticipantsBuilder Specifies abstract interface for creating parts of a productobject.ConcreteBuilder Constructs and assembles parts of the product byimplementing 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, includinginterfaces for assembling the parts into the final result.
25Intel Confidential25Consequences & ImplementationConsequences & ImplementationConsequences Hide the product’s internal representation It gives you finer control over the construction processImplementation Assembly and construction interface Empty methods as default in Builder (C++).
28Intel Confidential28AgendaAgendaHistory in a nutshellDesign pattern definitionsGoF example #1: Observer patternGoF example #2: Builder patternGoF example #3: Strategy patternUsing Design Patterns for SWdevelopmentSummary
29Intel Confidential29Strategy Design PatternStrategy Design PatternIntent Define a family of algorithms, encapsulate each one, and make theminterchangeable. Strategy lets the algorithm vary independently fromclients that use it.Motivation Many algorithms exist for breaking a stream of text (paragraph) intolines. Hard-wiring all such algorithms into the classes that require themisn’t desirable for several reasons:– Clients that need line breaking become more complex if they include the linebreaking code. The problem grows if a client should support multiplealgorithms.– Different line breaking algorithms will be appropriate at different times.– It’s difficult to add new algorithms and vary existing ones when linebreaking is an integral part of the client. We can avoid the problem by defining classes that encapsulate differentline breaking algorithms. An encapsulated algorithm is called a strategy.Example LIRA language specific type checking Gateview traversal algorithm
31Intel Confidential31Strategy Pattern ParticipantsStrategy Pattern ParticipantsStrategy Declares an interface common to all supportedalgorithms. Context uses this interface to call thealgorithm 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.
32Intel Confidential32Consequences & ImplementationConsequences & ImplementationConsequences Families of related algorithms An alternative to subclassing Strategies eliminate conditional statements Choice of implementations– Performance tradeoffs Potential communication overhead between Context andStrategyImplementation Set the strategy of the context via virtual interface (runtime) or template parameter (compile time). Pass state arguments to the strategy object, or pass thecontext object itself. An algorithm can have a default strategy
34Intel Confidential34Source 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
35Intel Confidential35AgendaAgendaHistory in a nutshellDesign pattern definitionsGoF example #1: Observer patternGoF example #2: Builder patternGoF example #3: Strategy patternUsing Design Patterns for SWdevelopmentSummary
36Intel Confidential36Using Design PatternsUsing Design PatternsProduct DefinitionRequirements GatheringAnalysisDesignImplementationIntegration & TestingDeployment & SupportDesign Patterns are appliedduring the Design phase ( )
37Intel Confidential37Using 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 listedWhen 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
38Intel Confidential38Using Design PatternsUsing Design PatternsGood Variance Design Patterns are expected to be adjusted to the designenvironment/problem domain of the system.– Forming the pattern language of the development team. Patterns application is expected to adjust itself to the concretecomposition 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: IdiomsBad Variance Design Pattern should not vary between different application to thesame 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 theimplementation code.– Using comments and pattern “keywords”
40Intel Confidential40Beyond Go4 PatternsBeyond Go4 PatternsMultiple 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 presentationNew patterns can be added based ondeveloper/team experience
41Intel Confidential41Alexander on Design Patterns (1/2)Alexander on Design Patterns (1/2)But still a fundamental question of practicality must lieat the forefront. Does all this thought, philosophy, helppeople to write better programs? For the instigators ofthis approach to programming too, as in architecture, Isuppose a critical question is simply this: Do the peoplewho write these programs, using alexandrian patterns,or any other methods,do they do better work? Are theprograms better? Do they get better results, moreefficiently, more speedily, more profoundly? Do peopleactually feel more alive when using them? Is what isaccomplished by these programs, and by the people whorun these programs and by the people who are affectedby them, better, more elevated, more insightful, better byordinary spiritual standards?
42Intel Confidential42Alexander on Design Patterns (2/2)Alexander on Design Patterns (2/2)In my life as an architect, I find that the single thingwhich inhibits young professionals, new students mostseverely, is their acceptance of standards that are too low.If I ask a student whether her design is as good asChartres, she often smiles tolerantly at me as if to say, “Ofcourse not, that isn’t what I am trying to do. . . . I couldnever do that.”Then, I express my disagreement, and tell her: “Thatstandard must be our standard. If you are going to be abuilder, no other standard is worthwhile. That is what Iexpect of myself in my own buildings, and it is what Iexpect of my students.” Gradually, I show the studentsthat they have a right to ask this of themselves, and mustask this of themselves. Once that level of standard is intheir minds, they will be able to figure out, for themselves,how to do better, how to make something that is asprofound as that.
43Intel Confidential43SummarySummaryDesign Patterns are a tool to help you writegood programsDesign Patterns provide a flexible “BKM”solution to recurring problemsDesign pattern provide insight andsolution guidelines to the designer, not asoftware library.Sharing a pattern language can help adesign team to create good programsDesign Patterns are in production usage inFETA/LVT products.
44Intel Confidential44ContributorsContributorsThanks to: Sergey Pimenov for explaining Gateview Observerpattern implementation Yulik Feldman and Noam Farkash for providinginformation on design pattern usage in LIRA and Forte2 Detect team members for continues effort to improve oursoftware design skills Special thanks to Jacob Katz for contributing LIRA typechecker example
45Intel Confidential45Where 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.shtmlBooks: Design Patterns Pattern-Oriented Software Architecture http://www.dreamsongs.com/NewFiles/PatternsOfSoftware.pdf– Assays on Design Patterns, including introduction by Alexander.
47Intel Confidential47Translator Design PatternTranslator Design PatternFady et. allFady et. allIntent Replace the behavior of a class dynamically into another behavior whilemaintaining the same interface clients expect. Translator class allowsmid-level classes to modify the behavior of lower level classes withoutimpacting higher level classes.Motivation An application processing a large collection of data objects issometimes required to modify the contents of a small subset of theobjects. The translator pattern enables the isolation of such modification to themodifying code. The rest of the application code (both the data objectsand processing application) remains unchanged.Example Forte2 Verilog writer– exlif to Verilog name translation. Gandalf waveform enumerated trace values
49Intel Confidential49Translator Pattern ParticipantsTranslator Pattern ParticipantsItem Defines the interface for objects that may be translateddynamically.ConcreteItem Concrete implementation of Item interface.Translator Implements Item interface. Maintains a reference to the Item being translated. Modifies the Item behavior.
50Intel Confidential50Consequences & ImplementationConsequences & ImplementationConsequences Translation is hidden from data processors. Avoids distributionspecial case handling to multiple data processors. Data processors depend on Item interface only (areindependent of Translator code). Translator is reused by multiple data processors, both at codelevel and object level.Implementation The Translator may keep a reference to the translated item orcache the translation. Translator for complex items may require implementing severaltranslation classes (e.g. IteratorTranslator,AttributeTranslator, ..). Translator for small classes (e.g. without virtual interface) maybe expensive. Consider using Flyweight pattern.