Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Design patterns intro


Published on

Published in: Technology, Design
  • Be the first to comment

Design patterns intro

  1. 1. 1Intel Confidential1Introduction toIntroduction toDesign PatternsDesign Patternsand applicationand application for object oriented SW designfor object oriented SW designAsa Ben-TzurWW01’2005
  2. 2. 2Intel Confidential2Presentation GoalsPresentation GoalsIntroduction to design patterns conceptIntroduction to using design patterns in objectoriented designIntroduction to GoF design patternsEnable attendees to efficiently self-learn designpatterns 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. 3Intel Confidential3AgendaAgenda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 SWdevelopmentSummary
  4. 4. 4Intel Confidential4Design Patterns HistoryDesign Patterns HistoryChristopher 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 - 1979Ward Cunningham and Kent Beck broughtAlexander’s concept to SW design in 1987 Five pattern language was used to develop a userinterface for Tektronix
  5. 5. 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
  6. 6. 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
  7. 7. 7Intel Confidential7AgendaAgenda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 SWdevelopmentSummary
  8. 8. 8Intel Confidential8Design Pattern Definition #1Design Pattern Definition #1Christopher 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.”
  9. 9. 9Intel Confidential9Design Pattern Definition #2Design Pattern Definition #2GoF:“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.”
  10. 10. 10Intel Confidential10GoF pattern elementsGoF pattern elementsPattern nameProblemSolutionConsequences
  11. 11. 11Intel Confidential11A simple pattern exampleA simple pattern exampleName: Sleepless TalkProblem: 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 
  12. 12. 12Intel Confidential12AgendaAgenda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 SWdevelopmentSummary
  13. 13. 13Intel Confidential13Observer Design PatternObserver Design PatternIntent 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 coupledExample Model-View architecture– Windows file explorer– Gateview root cause analysis annotation– Seqver mapping advisor equivalence classes annotation
  14. 14. 14Intel Confidential14Observer Pattern StructureObserver Pattern Structurecd ObserverObserver+ «pure» update() : voidSubject- m_observers: std::list<Observer*>+ «pure» attach(Observer*) : void+ «pure» detach(Observer*) : void# notify() : voidConcreteSubject- m_state: int+ getState() : void+ setState() : voidConcreteObserver- m_state: double+ update() : voidm_observers0..*m_subject«realize»
  15. 15. 15Intel Confidential15Observer 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. 16Intel Confidential16Observer Pattern CollaborationsObserver Pattern Collaborationssd Observer:ConcreteSubject :ConcreteObserver :ConcreteObserversetState()notify()update()getState()update()getState()
  17. 17. 17Intel Confidential17Consequences & 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 expensiverun time overheadImplementation Observing multiple subjects Subscribing for specific update events– “Observer with aspect”
  18. 18. 18Intel Confidential18Example: Gateview ExpandExample: Gateview Expandcd Gateview root cause analysisGateview+ attach(IExpandObserver*) : void+ detach(IExpandObserver*) : void# notifyOnExpand() : void+ attach(IDestroyObserver*) : void+ detach(IDestroyObserver*) : void# notifyOnDestroy() : voidExpandObserver+ «pure» update(string, string) : voidRootCauseManager+ update(string, string) : void«realize»m_expandObservers0..*
  19. 19. 19Intel Confidential19Source 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
  20. 20. 20Intel Confidential20AgendaAgenda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 SWdevelopmentSummary
  21. 21. 21Intel Confidential21Builder Design PatternBuilder Design PatternIntent 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
  22. 22. 22Intel Confidential22Builder Pattern StructureBuilder Pattern Structurecd BuilderDirector+ construct() : voidBuilder+ «pure» buildPart()ConcreteBuilder+ buildPart()+ getResult() : Product*«realize»m_builder
  23. 23. 23Intel Confidential23Builder Pattern ParticipantsBuilder Pattern ParticipantsBuilder 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.
  24. 24. 24Intel Confidential24Builder Pattern CollaborationsBuilder Pattern Collaborationssd BuilderClient:ConcreteBuilder:Directornew ConcreteBuildernew Director(ConcreteBuilder)construct()buildPartA()buildPartB()buildPartC()Product*:= getResult()
  25. 25. 25Intel Confidential25Consequences & 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. 26Intel Confidential26Example: Forte2 XML readerExample: Forte2 XML readercd Forte2XMLXmlReader+ XmlReader(IXmlConverter*)+ read(const char*) : boolXmlConverter+ «pure» convertElementBegin(const char*, const char**) : void+ «pure» convertElementEnd(const char*) : voidFlXmlConverter+ convertElementBegin(const char*, const char**) : void+ convertElementEnd(const char*) : voidgandalf::XmlConfigurationFile+ convertElementBegin(const char*, const char**) : void+ convertElementEnd(const char*) : void«realize»builder«realize»
  27. 27. 27Intel Confidential27Source 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. 28Intel Confidential28AgendaAgenda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 SWdevelopmentSummary
  29. 29. 29Intel Confidential29Strategy Design PatternStrategy Design PatternIntent 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
  30. 30. 30Intel Confidential30Strategy Pattern StructureStrategy Pattern Structurecd StrategyContext+ contextInterface()Strategy+ «pure» algorithmInterface()ConcreteStrategyA+ algorithmInterface()ConcreteStrategyB+ algorithmInterface()ConcreteStrategyC+ algorithmInterface()m_strategy«realize» «realize» «realize»
  31. 31. 31Intel Confidential31Strategy Pattern ParticipantsStrategy Pattern ParticipantsStrategy 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.
  32. 32. 32Intel Confidential32Consequences & 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 andStrategyImplementation 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
  33. 33. 33Intel Confidential33Example: Lira Type CheckerExample: Lira Type Checkercd TypecheckILanguageRules+ IsLegalLValue(MiscStateInfo*) : bool+ IsLegalRValue(MiscStateInfo*) : bool+ CheckObjectDeclaration(MiscStateInfo*) : boolIHDLLanguageRules+ IsLegalLValue(MiscStateInfo*) : bool+ IsLegalRValue(MiscStateInfo*) : bool+ CheckObjectDeclaration(MiscStateInfo*) : boolVerilogLanguageRules+ IsLegalLValue(MiscStateInfo*) : bool+ IsLegalRValue(MiscStateInfo*) : bool+ CheckObjectDeclaration(MiscStateInfo*) : boolCTypeChecker+ CTypeChecker(ILanguageRules&)+ TypeCheckExpression(MiscStateInfoe*) : boolm_languageRules«realize» «realize»
  34. 34. 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
  35. 35. 35Intel Confidential35AgendaAgenda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 SWdevelopmentSummary
  36. 36. 36Intel Confidential36Using Design PatternsUsing Design PatternsProduct DefinitionRequirements GatheringAnalysisDesignImplementationIntegration & TestingDeployment & SupportDesign Patterns are appliedduring the Design phase ( )
  37. 37. 37Intel Confidential37Using 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. 38Intel Confidential38Using Design PatternsUsing Design PatternsGood 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: IdiomsBad 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”
  39. 39. 39Intel Confidential39GoF Patterns UsageGoF Patterns UsagePattern Forte2 Lira GandalfAbstract Factory -(*) + -Builder + + +Factory Method - - +Singleton + + +Adapter -(*) + +Bridge - + -Composite + + +Flyweight - - +Command + - +Iterator + + +Observer + - +Strategy - + -Visitor + + -
  40. 40. 40Intel Confidential40Beyond 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 ondeveloper/team experience
  41. 41. 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?
  42. 42. 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.
  43. 43. 43Intel Confidential43SummarySummaryDesign Patterns are a tool to help you writegood programsDesign Patterns provide a flexible “BKM”solution to recurring problemsDesign pattern provide insight andsolution guidelines to the designer, not asoftware library.Sharing a pattern language can help adesign team to create good programsDesign Patterns are in production usage inFETA/LVT products.
  44. 44. 44Intel Confidential44ContributorsContributorsThanks 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
  45. 45. 45Intel Confidential45Where to get more informationWhere to get more informationIntel-U: Design Patterns (Hi-Tech)Web sites: Detailed Introduction by Brad Appleton:– Hillside group:– Pattern links:–Books: Design Patterns Pattern-Oriented Software Architecture– Assays on Design Patterns, including introduction by Alexander.
  46. 46. 46Intel Confidential46BackupBackup
  47. 47. 47Intel Confidential47Translator Design PatternTranslator Design PatternFady et. allFady et. allIntent 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
  48. 48. 48Intel Confidential48Translator Pattern StructureTranslator Pattern Structurecd TranslatorItem+ «pure» getAttribute()+ «pure» method()ConcreteItem+ getAttribute()+ method()Translator+ getAttribute()+ method()return translate( item->getAttribute() );item«realize» «realize»
  49. 49. 49Intel Confidential49Translator Pattern ParticipantsTranslator Pattern ParticipantsItem 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.
  50. 50. 50Intel Confidential50Consequences & ImplementationConsequences & ImplementationConsequences 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.
  51. 51. 51Intel Confidential51Source Code ExamplesSource Code Examples/vobs/gandalf/sti/sti/TraceItem.h/vobs/gandalf/sti/sti/TraceValueIterator.h/vobs/gandalf/view/waveform/Enumerated*