1 / 38

GoF Design Patterns

GoF Design Patterns. Presented By Dr. Shazzad Hosain. GoF Patterns. GoF stands for Gang-of-Four According to the four authors of “Design Patterns” book Twenty three GoF patterns such as Adapter Factory Singleton Strategy Composite Facade

bat
Télécharger la présentation

GoF Design Patterns

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. GoF Design Patterns Presented By Dr. Shazzad Hosain

  2. GoF Patterns • GoF stands for Gang-of-Four • According to the four authors of “Design Patterns” book • Twenty three GoF patterns such as • Adapter • Factory • Singleton • Strategy • Composite • Facade • Observer/Publish-Subscribe/Delegation Event Model

  3. Adapter • Context/Problem: How to resolve incompatible interfaces, or provide a stable interface to similar components with different interfaces? • Solution: Convert the original interface of a component into another interface, through an intermediate adapter object.

  4. Adapter

  5. Adapter • Adapter pattern is a specialization of Polymorphism, Indirection and Protected Variations (GRASP Patterns)

  6. Factory • Context/Problem: Who creates the adapters? How to determine which class of adapter to create, such as TaxMasterAdapter or GoodAsGoldTaxProAdapter? • Solution: Create a Pure Fabrication object called a Factory that handles the creation. • Design Principle: Design to maintain a separation of concerns.

  7. UML Style

  8. Advantages of Factory • Separate the responsibility of complex creation into cohesive helper objects. • Hide potentially complex creation logic • Allow introduction of performance-enhancing memory management strategies, such as object caching or recycling.

  9. Singleton • Context/Problem: Exactly one instance of a class is allowed – it is a “singleton”. Objects need a global and single point of access. • Solution: Define a static method of the class that returns the singleton.

  10. Implementation and Design Issues Lazy initialization public class ServiceFactory { static ServiceFactory instance = null ; // other variable definition public static synchronized ServiceFactory getIntance () { if (instance == null) { instance = new ServiceFactory() ; } return instance ; } // other methods } Eager initialization public class ServiceFactory { private static ServiceFactory instance = new ServiceFactory (); public static ServiceFactory getIntance () { return instance ; } // other methods }

  11. Lazy vs. Eager Approach • Lazy one is preferable • Creation work (and perhaps holding on to “expensive” resources is avoided in the instance is never actually accessed. • The getInstance () lazy initialization sometimes contains complex and conditional creation logic.

  12. Static Instance vs. Static Method public class ServiceFactory { static ServiceFactory instance = null ; // other variable definition public static synchronized ServiceFactory getIntance () { if (instance == null) { instance = new ServiceFactory() ; } return instance ; } // other methods } public class ServiceFactory { private static ServiceFactory instance = new ServiceFactory (); public static ServiceFactory getIntance () { return instance ; } // other methods }

  13. Static Instance vs. Static Method • Static instance is preferred for the following reasons: • Static methods are not polymorphic (virtual) and don’t permit overriding in sub-classes in most languages. • Most OO remote communication mechanisms, e.g. Java RMI, only support remote-enabling of instance methods, not static methods. • You create an object X as singleton, but latter on discovered that it is should not be a Singleton i.e. multiple instances needed. Thus, instance-side solution offers flexibility

  14. Use of Adapter, Factory and Singleton public class Register { public void initialize () { // do some work …………….. accAdapter = ServiceFactory.getInstance().getAccountingAdapter () ; // do some work …………….. } // other methods }

  15. GoF Patterns • Adapter • Factory • Singleton • Strategy • Composite • Facade • Observer/Publish-Subscribe/Delegation Event Model

  16. Strategy • Context/Problem: How to design for varying, but related, algorithms or policies? How to design for the ability to change these algorithms or policies? • Solution: Define each algorithm/policy/strategy in a separate class, with a common interface.

  17. Strategy Public Class Sale { LinkedList list = new LinkedList () ; void addSalesLineItem (SalesLineItemsli) { list.add (sli) ; } intgetTotal () { total = 0 for each item in list total = total + item.getSubTotal () ; } }

  18. Public Class Sale { LinkedList list = new LinkedList () ; void addSalesLineItem (SalesLineItemsli) { list.add (sli) ; } intgetTotal () { total = 0 for each item in list total = total + item.getSubTotal () ; } } Strategy Public Class Sale { int total = 0 ; LinkedList list = new LinkedList () ; ISalePricingStrategyisps = (ISalePricingStrategy) new AbsoluteDiscountOverTrresholdPricingStrategy () ; void addSalesLineItem (SalesLineItemsli) { list.add (sli) ; } intgetPreDiscountTotal () { return total ; } intgetTotal () { total = 0 for each item in list total = total + item.getSubTotal () ; return isps.getTotal (this) ; } }

  19. Public Class Sale { LinkedList list = new LinkedList () ; void addSalesLineItem (SalesLineItemsli) { list.add (sli) ; } intgetTotal () { total = 0 for each item in list total = total + item.getSubTotal () ; } } Strategy Public Class Sale { int total = 0 ; LinkedList list = new LinkedList () ; ISalePricingStrategyisps = (ISalePricingStrategy) new AbsoluteDiscountOverTrresholdPricingStrategy () ; void addSalesLineItem (SalesLineItemsli) { list.add (sli) ; } intgetPreDiscountTotal () { return total ; } intgetTotal () { total = 0 for each item in list total = total + item.getSubTotal () ; return isps.getTotal (this) ; } }

  20. Creating a Strategy with a Factory

  21. Composite • Example: Suppose a store has the following policies in efeect today: • 20% senior disocunt policy • Preferred customer discount of 15% off sales over $400 • Today there is $50 off purchases over $500 • Buy 1 case of Darjeeling tea, get 15% discount off of everything • Suppose a senior who is also a preferred customer buys 1 case of Darjeeling ea and $600 of veggieburgers. • What pricing policy should be applied? • Policy may be different • Best for the customer (lowest price) • Best for the store (highest price), probably during recession

  22. Composite • Context/Problem: How to treat a group or composition structure of objects the same way (poly-morphically) as a non-composite (atomic) object? • Solution: Define classes for composite and atomic objects so that they implement the same interface.

  23. Collaboration with a Composite

  24. GoF Patterns • Adapter • Factory • Singleton • Strategy • Composite • Facade • Observer/Publish-Subscribe/Delegation Event Model

  25. Strategy • Context/Problem: How to design for varying, but related, algorithms or policies? How to design for the ability to change these algorithms or policies? • Solution: Define each algorithm/policy/strategy in a separate class, with a common interface.

  26. Façade • Context/Problem: A common, unified interface to a disparate set of implementations or interfaces – such as within a subsystem – is required. There may be undesirable coupling to many things in the subsystem, or the implementation of the sub-system may change. What to do? • Solution: Define a single point of contact to the subsystem – a façade object that wraps the subsystem. • Example: “Rule engine” subsystem, whose specific implementation is not yet known. While creating a line item may be several rules may need to be checked.

  27. Façade Public Class Sale { public void makeLineItem (ProductSpecification spec, int quantity) { SalesLineItemsli = new SalesLineItem (spec, quantity) ; if (POSRuleEngineFacade.getInstance ().isInvalid ( sli, this ) ) return ; lineItem.add ( sli) ; } // ….. } // end of class

  28. Façade • Rule engine subsystem may contain one to hundreds of classes.

  29. Observer/ Publish – Subscribe/Delegation Even Model • A probable solution • When Sale changes its total, it sends a message to a window, asking to refresh its display • But then Sale object, a domain model object, knows an UI object • Low coupling is not maintained

  30. Another Example • For Alarm Clock the following things needs to do • Show a display dialog box • Beep or ring a bell • Run a reliability watch dog • For upcoming train / plane schedule • Display the schedule at different display boards • Automatically announce the time thorough mikes

  31. Observer/ Publish – Subscribe /Delegation Even Model • Context/Problem: Different kinds of subscriber objects are interested in the state changes or events of a publisher object, and want to react in their own unique way when the publisher generates an event. Moreover, the publisher wants to maintain low coupling to the subscribers. What to do? • Solution: Define a “subscriber” or “listener” interface. Subscribers implement this interface. The publisher can dynamically register subscribers who are interested in an event, and notify them when an event occurs.

  32. Subscribe and consume Registration Desk Registration Publish

  33. Who is the observer, listener, subscriber and publisher

  34. Subscribe and consume Registration Desk Publish

  35. Assignment • Design and implement one of more use cases so that you use the following patterns • Singleton • Factory • Strategy • Publish - Subscribe

  36. References • Chapter 23 of “Applying UML and Patterns – An Introduction to Object-Oriented Analysis and Design and the Unified Process” – by Craig Larman

More Related