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.

Software Design Patterns


Published on

Discusses some software design patterns with example

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

Software Design Patterns

  2. 2. “Descriptions of communicatingobjects and classes that arecustomized to solve a generaldesign problem”-- Gamma, et. al.2
  3. 3.  The Pattern Name The Problem it solves The Solution it provides The Consequences (good and bad) of using it3
  4. 4. 4CHANGES…Patterns should be able to deal with changes.Changes can come from many different sources:- New vendor- New Technology- New views-New complexityof the application domain.- Errors
  5. 5. There are 3 types of pattern … Creational: address problems of creating an objectin a flexible way. Separate creation, fromoperation/use. Structural: address problems of using O-Oconstructs like inheritance to organize classes andobjects Behavioral: address problems of assigningresponsibilities to classes. Suggest both staticrelationships and patterns of communication(use cases)
  6. 6. A modifiable design enables• An iterative and incremental development cycle,which allows Concurrent (aka simultaneous) development Risk management Flexibility to change• The software developer to minimize theintroduction of new problems when fixing oldones.• The software developer to deliver morefunctionality after initial delivery.6
  7. 7.  Low coupling and high cohesion Clear dependencies between classes Explicit assumptions.How do design patterns help? They are generalized from existing, i.e. proven,systems. They provide a shared vocabulary to designers. They provide examples of modifiable designs. They use, principally, Abstract classes Delegation & inheritance7
  8. 8. 8Common architectural patternsFaçade StrategyProxy Abstract FactoryBridge CommandAdapter Composite
  9. 9. 9Patterns ExplainedSingletonFaçadeFactoryAdapterBridge
  10. 10. Name: SingletonProblem:How can we guarantee that one and only oneinstance of a class can be created?Context: In some applications it is importantto have exactly one instance of a class, e.g. sales ofone company.
  11. 11. Forces: Can make an object globally accessible as aglobal variable, but this violates encapsulation.Could use class (static) operations and attributes, butpolymorphic redefinition is not always possible.Solution:Create a class with a class operation getInstance().When class is first accessed, this creates relevantobject instance and returns object identity to client.On subsequent calls of getInstance(), no newinstance is created, but identity of existing object isreturned.
  12. 12. Singleton-uniqueInstance-singletonData+getInstance( )+getSingletonData( )+singletonOperation( )-Singleton( )Object identifier for singletoninstance, class scope or staticReturns object identifier forunique instance, class-scopeor staticPrivate constructor only accessiblevia getInstance()getInstance( ) {if ( uniqueInstance == null ){ uniqueInstance = new Singleton( ) }return uniqueInstance}
  13. 13. Class Singleton {private static Singleton uniqueInstance = null;private Singleton( ) { .. } // private constructorpublic static Singleton getInstance( ) {if (uniqueInstance == null)uniqueInstance = new Singleton();// call constructorreturn uniqueInstance;}}Example: Code
  14. 14.  To specify a class has only one instance, wemake it inherit from Singleton.+ controlled access to single object instancethrough Singleton encapsulation+ Can tailor for any finite number of instances+ namespace not extended by global variables- access requires additional message passing- Pattern limits flexibility, significant redesign ifsingleton class later gets many instances
  15. 15. 15A sculpture is singleton
  16. 16. Name: FaçadeProblem:How can we access a large number of classeswith a complex internal interaction in a simplebut safe way?Solution: Introduce a dedicated interface classthat simplifies the view of the class collection.
  17. 17.  Provides a unified interface to a set of objects in asubsystem. A façade defines a higher-level interface that makes thesubsystem easier to use (i.e. it abstracts out all the“messy” details) Façades allow us to provide a closed architecture.17Bad!Good!
  18. 18. Facadesubsystem classes
  19. 19. 19Façade interface toclient provides one (orfew) method(s) thatallows the client toinvoke the subsystemsservices.
  20. 20. <<façade>>SecurityManager+addAccessRight()+addActor()+addActorRole()+removeActor()AccessRight+addAccessRight()Actor+addActor()+removeActor()+changeSalary()ActorRole+addActorRole()Method not in FacadePattern Name
  21. 21. 21Home Theatre system and compiler are examples ofFaçade implementation
  22. 22. 22Compilercompile(s)Parse Nodecreate()Lexical AnalysisgetToken()Code Generatorcreate()ParsergenerateParseTree()Optimizercreate()Compiler
  23. 23. 23Example – Home TheaterLots of classesand interactions,plus many interfaces.
  24. 24.  Clients communicate with the subsystem by sendingrequests to Façade which forwards them to theappropriate subsystem object(s). Although subsystem objects perform actual work,Façade may have to translate its interface to subsysteminterfaces. Clients that use the Façade don’t have to access itssubsystem objects directly.
  25. 25.  Usually only one Façade object is required. Thus aFaçade object is often a singleton. Factory pattern can be used with Façade to provide aninterface for creating subsystem objects in a subsystemindependent way. Factory can also be used as an alternative to Façade tohide platform-specific classes. Mediator pattern is similar to Façade in abstractingfunctionality of classes.
  26. 26. Name: (Abstract) FactoryProblem: Provide an interface for creatingfamilies of related or dependent objectswithout specifying their concrete classes. Control instantiation Singleton is a special case of Factorywhereonly one object can be created.
  27. 27. AbstractProductConcreteProduct1AbstractFactoryConcreteFactoryFactoryMethod()AnOperation()FactoryMethod()Product =FactoryMethod()return newConcreteProduct()
  28. 28.  Normally, a single instance of aConcreteFactory class is created atruntime. This creates product objects having aparticular implementation. To create different product objects, clientsshould use a different concrete factory. AbstractFactory defers creation ofproduct objects to its ConcreteFactorysubclasses.
  29. 29. MyClasscreateObjectOfRequiredClass():RequiredClassFactory design patternClient RequiredClassFactory Class Modelcreate objects
  30. 30.  E.g. create objects of different types We can order a Car and get anAston Martin, MG, Jaguar etc We don’t know which factory builds thecar, just that they implement CarFactory.Owner has created the actual factoryinstance.
  31. 31. // we have a reference to ownerCarFactory aFactory = owner.makefactory();Car myCar =aFactory.makeCar(“AstonMartin”);class BritishFactory implements CarFactory{public Car makeCar(String b) throws Exception {if(b.equals(“AstonMartin”)) return newAstonMartin();else if (..) return ..;else throw new Exception(b + “doesn’texist”);}}
  32. 32. Class AstonMartin extends Car {}Class Jaguar extends Car {}Interface CarFactory {Public Car makeCar(String b) throws Exception;}
  33. 33. 33Aston Martin Jaguar
  34. 34.  Abstract Factory classes are oftenimplemented with the Factory Methodpattern. Can also be implemented using thePrototype pattern. A concrete factory is often a Singleton.Comments
  35. 35. 35Pattern: AdapterSuppose a client objects expect a certain interface to beprovided by called object.However, the interface of the called object differs fromwhat the clients expect, and cannot be changed.How may this situation be improved, i.e. how may theinterface satisfy the clients?
  36. 36. 36
  37. 37.  Transforms the interface of the target class into anotherinterface that the client classes expect. Adapter lets classes work together that could nototherwise because of incompatible interfaces. Used to provide a new interface to existing legacy (i.e.old) software components (aka interface engineering,re-engineering). Adapter also known as a wrapper37
  38. 38. 38Adapter PattenContext:1. Want to use an existing class without modifying it – call it the“legacy” class2. But context in which you want to use the legacy class requiresconformance to a target (i.e. new) interface that is different fromthat which the legacy provides.3. However, the target interface and legacy interface areconceptually related.Solution:1. Define an adapter class that implements the target interface.2. The adapter class holds a reference (delegates) to the legacyclass.It translates (new) target requests (or method calls) from clientclasses to (old) legacy requests (or method calls).
  39. 39. 39Participants of the Adapter Pattern• Target: Defines the application-specific interface thatclients use.• Client: Collaborates with objects conforming to thetarget interface.• Legacy: Defines an existing interface that needsadapting.• Adapter: Adapts the interface of the legacy class to thetarget interface.
  40. 40. Bind an Adapter class with the Legacy class The Adapter class implements the ClientInterface expected bythe client. It then delegates requests from the client to the Legacyclass and performs any necessary conversion. ClientInterface could be a Java/C# interface, or an abstractclass40ClientTargetClientInterfaceRequest()LegacyExistingRequest()AdapterRequest()Legacy classdelegationinheritance
  41. 41. 41Interface inheritance is use to specify the interface of theAdapter class – and then delegation is used to referencethe Legacy classLegacy classsupporting oldinterfaceClass supporting newinterfaceInheritanceDelegation
  42. 42. 42ExampleTurkeys do not quack, theygobble. Turkeys can fly but foronly short distances.How can we adapt the Turkey class to behave like aDuck class?
  43. 43. 43duck quack becomes turkey gobbleduck fly becomes fivetimes turkey flyAdapt the Turkey class to have the same interface as Duck.i.e. have methods quack() and fly()
  44. 44. 44Pattern: BridgeClient objects expect a constant interface to be providedby some called object.However, the actual implementation of the interface mayvary – there may be lots of different implementations,depending on the circumstances.How may this situation be satisfied?
  45. 45.  Use a Bridge pattern to decouple anabstraction from its implementationso that both can vary independently. Also known as “handle/body” pattern Allows different implementations of an interfaceto be decided upon dynamically.45
  46. 46. 46Problem- Want to decouple an abstraction (i.e. class interface) from itsimplementation, allowing them to vary separately.Context- Want to change implementation details at run-time without impact toclients classes.Solution- Use delegation from an interface class to an implementation class.Consequences- Can change (or add) interface without re-implementing.- Can change implementation, but not impact interface for clients.
  47. 47. 47InheritanceImplementorAbstractionimplementsImplementorA ImplementorBClientThe Abstraction class defines the interface visible to client.The Implementor class is an abstract implementation that defines thelower-level methods available to Abstraction – namely different“concrete” implementations such as ImplementorA or ImplementorBDelegation
  48. 48. 48ExampleSupporting multiple Database Vendors with a BridgeLeagueStoreImplementorLeagueStoreimplementsXML StoreImplementorSQL Server StoreImplementorJDBC StoreImplementorArenaLeagueStore is the interface class to the patternAbstract interfaceprovides commoninterface
  49. 49.  The bridge pattern is used to provide multipleimplementations under the same interface. Decouples an interface from the implementation so thatimplementation can be substituted, possibly at runtime. Example: Interface to a component that is incomplete,not yet known, or unavailable during testing49
  50. 50. 50Consider problem of incrementally developing, testingand integrating subsystems realized by different projectteams.Subsystems may be completed at different times,delaying the integration of all subsystems until the lastone has been completed.To avoid delay, projects often use a stubimplementations in place of a specific subsystem sothat the integration tests can start even before thesubsystems are completed.
  51. 51. 51Example of the bridge pattern
  52. 52.  Similarities: Both are used to hide the details of the underlyingimplementation. Difference: The adapter pattern is geared towards makingunrelated components work together Applied to systems after they are designed (reengineering,interface engineering). A bridge, on the other hand, is used up-front in adesign to let abstractions and implementations varyindependently. Engineering of an “extensible system”. New components can be added to the system, even if theseare not known at analysis or system design time.52