/
Design Patterns Spring 2017 Design Patterns Spring 2017

Design Patterns Spring 2017 - PowerPoint Presentation

delilah
delilah . @delilah
Follow
67 views
Uploaded On 2023-09-23

Design Patterns Spring 2017 - PPT Presentation

1 Useful books The Gang of Four book 1994 Head First Design Patterns Book 2004 2 A design pattern is a general solution to a common problem in a context What you have What you want ID: 1020095

factory design class object design factory object class pattern objects create singleton patterns pizza created composite instance code abstract

Share:

Link:

Embed:

Download Presentation from below link

Download Presentation The PPT/PDF document "Design Patterns Spring 2017" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

1. Design PatternsSpring 20171

2. Useful booksThe “Gang of Four” book1994Head First Design Patterns Book20042

3. A design pattern is a general solution to a common problem in a context.What you haveWhat you wantWhat you can do3

4. Design Pattern Index4CreationalStructuralBehaviouralFactory MethodAdapterTemplateAbstract FactoryBridgeStrategyBuilderCompositeCommandSingletonDecoratorStateMultitonFacadeVisitorObject poolFlyweightChain of ResponsibilityPrototypeFront controllerInterpreterProxyObserverIteratorMediatorMemento

5. MotivationA cook knows a lot of recipesThey look up the ones they forgetDesign patterns are recipes for programmersHow can you choice a good strategyIf you don’t know the range of available strategiesHow can you talk about the choicesIf they don’t have well understood namesAngel cakeInstruction: Fold don’t stir..I used a food blender because it was thereMy angel cake was afterwards remembered as a pancake5

6. WARNING: Overuse of design patterns can lead to code that is downright over-engineered. Always go with the simplest solution that does the job and introduce patterns only where the need emerges.6[Head First Design Patterns]

7. Good design principlesProgram to interfaces not to an implementationSeparate what changes from what does notEncapsulate what varies behind an interfaceFavor composition over inheritanceLoosely couple objects that interactClasses should be open for extension, but closed for modificationEach class should have one responsibilityDepend on abstractions, not concrete classes7

8. Good use of Design Pattern PrinciplesLet design patterns emerge from your design, don’t use them just because you shouldAlways choose the simplest solution that meets your needAlways use the pattern if it simplifies the solutionKnow all the design patterns out thereTalk a pattern when that simplifies conversation8

9. Creational Design Patterns9

10. Factory Design Pattern GoalsSeparate what changes from what does notEncapsulate what varies behind an interfaceDepend on abstractions, not concrete classesLoosely couple objects that interactDesign should be open for extension but closed to modification10

11. Problems with using newSo myClass = new MyClass(….) is bad..It might be invoked from many placesIt might be replaced by new MyBetterClass(…) Many different subclasses might existWant to be able to decide the subclass at runtimeWant to create the correct subclass not old superclassWithout ugly code present everywhereWant perhaps to pass around a tool to create whatever the tool is designed to createMay not know what to create until run timeMay wish to identify classes by GUID’s, and register them11

12. Factory SolutionWrap code that creates objects inside a methodInterface = createMyClass(parameters) We can change the class created now in one placeParameter can identify what to createMight make createMyClass staticIe. static MyClass::createMyClass(…)But this reassociates the creation with the class If we want to pass method around put it in a factory object (clearer than pointer to method)12

13. 13

14. 14

15. AdvantagesProtects higher level code from ugly lower level detail such as which class should be createdAny change to the class created is made just onceWe can make the objects to create dynamicSimply pass a pointer to a factory object to the things that need to create the objectsThen the factory object becomes conceptually the instruction regarding what to createWe can override createMyClass in subclasses or use it in any other way we wish (ie. Use with template design pattern described later)15

16. Factory Pattern DefinitionThe Factory Method Pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate.Question: How should we delete objects created using a factory.Should we have a matching deleteMyClass()Should it make the pointer to the object nullOr should we use reference counting??16

17. Abstract Factory PatternSuppose we have a factory that can be told what objects to create from a choice of all within a frameworkThen we can create a new factory with the same “abstract” interfaces to create the same objects but from a very different frameworkDeciding which framework to use then becomes deciding which concrete instantiation of an abstract factory class to use17

18. 18

19. AdvantagesProtects us from creating components from many frameworks that can’t talk to each otherMakes it easy to decide at run time which framework we want to useThe framework chosen is transparent to all higher level codeMakes it easier to add new frameworks if we have need to do so19

20. ExampleDomino’s pizza’s are flatPizza Hut’s pizza’s are deep dish pizza’sBoth offer a variety of subclasses of pizzasIf we create an abstract factorySubclass a Domino’s pizza factorySubclass a Pizza Hut’s pizza factoryWe won’t need to create a pizza store for eachJust give each pizza store a different factoryAdding support for New York PizzaPiece of cake (pizza)20

21. 21This is employing the template design pattern (described later)

22. This is the template approachCan also pass factory to pizzastoreSave it internallyThis is the strategy design pattern22

23. Abstract Factory DefinitionThe Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes 23

24. Builder Design PatternWant to construct a complex object built from many component objectsWant to say what must be constructedBut don’t want to expose the details of how the object is composed from its componentsUse a builder object that keeps track of the object being built and allows construction to be performed via method calls in the builder24

25. 25

26. 26

27. AdvantageProgramming to an interfaceObjects built according to actions, not codeThe composite objects are be constructed differently within the builder transparentlyAdditional useful structures such as indices, hashing etc. can be implemented as needed inside the builderBut extra layer of indirection27

28. Builder DefinitionThe Builder Pattern encapsulates the construction of a product and allows it to be constructed as a sequence of steps.28

29. Singleton Design PatternEnsure there is only one instance of an objectEnsures that global objects are not misusedUse a factory to construct itHave the factory return it if already constructedMake the constructor(s) private to the classPut the factory method in the classBe careful to ensure logic is thread safe29

30. 30= null;

31. 31The constructor is private so it can’t be invoked directly from outside of the class

32. Singleton DefinitionThe Singleton Pattern ensures that a class has only one instance, and provides a global point of access to itNeed to ensure that the assignment of the single instance to a static variable (as well as other operations) are thread safe if might be using singleton in multiple threadsQuestion: how might a singleton object be deleted32

33. Multiton PatternGeneralisation of the Singleton Design PatternCreates a singleton object associated with a given keyEnforces a one-to-one mapping between keys and the object (if present) associated with that key33

34. Object Pool Design PatternConsider implementing if you have a lot of objects of the same type being constantly created and deletedFactory maintains a list of constructed but now release objectsCreation involves returning an object from the pool if it exists else creating a new objectDeletion involves adding deleted object to the pool for later reuse34

35. AdvantagesMalloc/new are expensive operationsDramatically reducing the need to create memory can produce significant performance improvementCan return elements of a large array instead of creating each element independentlyCan also manage the maximum number of objects of a type created more easily and potentially transparentlyCan potentially control number of threads created35

36. PrototypeA collection of proto-typical instantiations of a class existTo create a new instance of one of these classes the class is cloned from its prototypeOr if the class has no state it can simply be reused in many places (see: flyweight pattern)36

37. 37

38. AdvantagesHow an instance of a class is to be created is fully determined by referring to an exampleThis might simplify the construction of a very complex objectNew prototypes can be added to the listAfterwards easy to create copies of theseUsers may choose the prototype they wantCan visually show the choices easilyBut copying an object can also be complicated38

39. Structural Design Patterns39

40. Adapter40usesuses wants to use

41. AdapterIntent: “Convert the interface of one class to make it compatible with another class.”Motivation: Components often have incompatible interfaces that cannot be used by a client but also cannot be modified.Applicability:When an intermediate representation between one component and another is requiredWhen you want to isolate a client from changes in an external component’s interface41

42. AdapterTwo kinds of adapters:Object adapters (use composition)Class adapters (use multiple inheritance)42

43. Object Adapter43[en.wikipedia.org]

44. Class Adapter44[en.wikipedia.org]

45. AdapterParticipants:Client: Calls the adapter; is completely isolated from the adaptee.Adapter: Forwards calls between client and adapter. The adapter may have to interact with multiple classes.Adaptee: A component being adapted.45

46. AdapterThere might be no exact match between old and new interfaces:Clients have to watch for potential exceptions46

47. Bridge Design PatternSeparates abstraction from its implementationThe abstraction can be very different from the implementationThe abstraction uses code to “bridge” the differencesReplaces is-a inheritance / implementation relationship with has-as composition relationshipEssentially a wrapper hiding implementationUseful when the implementation might be selectable or switchable at run time47

48. 48One usage of strategy design pattern

49. Composite Design PatternGiven a hierarchy implement the same interface on every member of this hierarchy even if members differSubclass from this common functionalityDo not distinguish between actions on a leaf and actions on a subtreeEg . Move location of leaf / subtreeTraverse all nodes in/under nodePrint tree49

50. 50

51. 51

52. Composite DefinitionThe Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets client treat individual objects and composition of objects uniformly, irrespective of how the objects within the hierarchy differ.52