Transcription
IMPORTANT NOTICE TO STUDENTSThese slides are NOT to be used as a replacement for student notes.These slides are sometimes vague and incomplete on purpose to spark class discussionsGang of Four (GoF)OO Design PatternsCS 446/646 ECE452May 11th, 2011WATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCE
MotivationObject Oriented Analysis (OOA) domain problem designed as (domain) objects–––addresses the functional challengeswhat a system doesprovides guidance for implementationObject Oriented Design (OOD) domain problem solved as (implementation) objects––addresses the implementation challengeshow a system realizes OOAWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE4522
MotivationHow can we improve OOD identify common characteristics– creation, structure, behaviour & interactionsdesign patterns (design reuse)–––generic blueprints (micro architecture)language and implementation independenttwo main catalogues GoF: Gang of Four (Gamma, Helm, Johnson, Vlissides, 1995)POSA: Pattern Oriented Software Architecture (Buschmann, etal.; Wiley, 1996)WATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE4523
MotivationWhat is a Design Pattern common solution to a reoccurring problem in designAnatomy name problem/motivation solution consequences & tradeoffs which ones are important for us?WATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE4524
Design Patterns ClassificationGoF Design jectscopeWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE4525
Design Patterns ClassificationGoF Design actory MethodAdaptor - classBehavioralInterpreterTemplate MethodAbstract FactoryAdaptor-objectChain of HERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE4526
Design Patterns Classification“Purpose” based classification creational:– structural– concerns with creation process of objects & classescomposition of classes & objectsbehavioral–characterizes interaction & responsibility of objects &classesWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE4527
Design Patterns Classification“Scope” based classification decided if the pattern applies to mainly classes or objectsTwo categories class scope–– relationship between classes & subclassesstatically defined at run-timeobject scope––object relationships (what type?)can be manipulated at runtime (so what?)WATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE4528
Design Patterns ClassificationCreational class Creational objectdefers object creation tosub-classes (factorymethod)Structural class inheritance to composeclasses (adapter)CHERITON SCHOOL OFCOMPUTER SCIENCE deals with objectassembly (adapter)Behavioral objectuses inheritance todescribe flow of control,algorithms (template)WATERLOOdefers object creation toother objects (abstractfactory)Structural objectBehavioral class CS446/646 ECE452group of objects workingtogether to carry out atask (iterator)9
SingletonIntent “ensure a class only has one instance, and provide aglobal point of access to it.”ConstructionWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45210
SingletonIntent“ensure a class only has one instance, and provide aglobal point of access to it.” Constructionpublic class Singleton {private static final Singleton INSTANCE new Singleton();// Private constructor prevents// instantiation from other classesprivate Singleton() {}}public static Singleton getInstance() {return INSTANCE;}WATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45211
SingletonAdvantages controlled access to the class instance(s)– can dictate who, and when a client can accessrefinement of functionality–via inheritance/subclassWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45212
SingletonAdvantages variable number of instances––the getInstance() method needs modificationwhat else needs to change?WATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45213
SingletonA closer look at Singleton reuse separation of concerns global presence stateful vs. stateless multiple instances life cycleWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45214
Singleton – A Closer LookReuse coupling–––results in tighter couplingcouples with the exact type of the singleton objectpass by reference to reduce coupling?WATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45215
Singleton – A Closer LookReuse coupling–––results in tighter couplingcouples with the exact type of the singleton objectpass by reference to reduce coupling?public void doSomething(){Worker worker Worker.getInstance();worker.perform();}public void doSomething(Worker worker){worker.perform();}WATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45216
Singleton – A Closer LookReuse inheritance––easy to extend functionality in subclassesnot easy to override the object instance in subclassesWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45217
Singleton – A Closer LookSeparation of concerns singleton class responsible for creation– acts as a builder/factorywhat if we were to separate the two concerns–example database connection as a singletonsystem 1 uses a singleton to ensure only a single databaseconnectionsystem 2 needs to connection pool of 10 databases connectionsWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45218
Singleton – A Closer LookGlobal presence provides a global access point to a service––aren't global variables bad?can be accessed from anywhere not part of method signature–– violation of layered accessdependency is not obviousrequires code inspectiona large system may require many singletons–use a registry/repositoryWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45219
Singleton – A Closer LookStateful singleton same as a global variable in principle– access concerns–– aren't global variables bad?synchronizationconcurrency – multiple threaded using a singletonmutable vs. immutable stateStateless singleton better then stateful can we have a stateless singleton?WATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45220
Singleton – A Closer LookMultiple instances distributed systems–– is it possible to have a true singleton in a distributedsystem?global registries/repositorieslanguage (Java) specific concerns–––initialization – has to be thread safeserializationclass loadersWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45221
Singleton – A Closer LookLife-cycle & life span creation– singletons are long lived––– lazy initializationas long as an application's life spanregistries can outlive applicationsunit testing requires short lived statelanguage (Java) specific concern––reloading singleton class (servlets)loss of stateWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45222
SingletonWhen can I use a singleton considerations[1]––– will every user use this class exactly the same way?will every applications ever need only one instance?should the clients be unaware of the applicationexamples–––Java Math class (stateless – static class)top level GUI (window/frame)logging[1] e.htmlWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45223
AdapterIntent “convert the interface of a class into another interface.Adapter lets classes work together that couldn't otherwisebecause of incompatible interface” also known as “wrapper” boolean values can be represented by––{1,0}, {true, false}, {yes, no}does this qualify as an adapter?WATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45224
MotivationNeed to add “Text” capability to our drawing editor.Consider an off the shelf TextView componentWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45225
MotivationObservations can be done in two ways––object composition (shown above)inheritance Shape provides “interface” and TextView provides animplementationLets try to draw this?WATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45226
Adapter – ClassRequirement requires multiple inheritancewhat about implementations that do not support multipleinheritance (Java)?WATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45227
Adapter – ObjectRequirement via object compositionWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45228
Adapter – Class vs. ObjectClass commitment to aconcrete adaptee class– not to its subclasses(class hierarchy) can use many adaptees– allows for specialization– Objectincluding sub-classesharder to override theadaptee behavior–why?how?static in natureWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45229
Adapter – Class vs. ObjectWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45230
Adapter & Dependency InversionDependency Inversion (DI) decouple high level layer from lower level rUtilitylayerSimple LayersWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCEAbstract LayersCS446/646 ECE45231
Dependency Inversion ExampleImplications Button implementationrelies on Lampany changes to Lamp willimpact Buttonwhat if we want to reuseButton class with adifferent component–such as a motorWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45232
Dependency Inversion ExampleDependency Inversion to Rescue looks good (?) still a dependency leftWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45233
Dependency Inversion ExampleObservation adapter enhanced the design–increased re-usability at the price of complexityWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45234
AdapterHow much adaptation is reasonable?WATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45235
BridgeIntent “decouples an abstraction from its implementation so thetwo can vary independently”does this not sounds like an adapter?–will take a closer look laterWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45236
BridgeWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45237
BridgeBridgeWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45238
Bridge ExampleProblemSolution via inheritanceproblem1: what if we have tosupport another platform?problem2: client code is tied toan implementation.For portable code, the clientshould not refer to animplementationWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45239
Bridge ExampleSolution: Use bridge pattern to place abstraction andimplementation in two different hierarchiesWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45240
Bridge ExampleSolution: Use bridge pattern to place abstraction andimplementation in two different hierarchiesBridgeWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45241
BridgeFeatures flexible binding between abstraction & implementation two class hierarchies clients are decoupledWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45242
Adapter & BridgeCommon Elements flexibility via indirection request forwardingWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45243
Adapter & BridgeDifference in intent adapter–––– resolves incompatibilities between two existing interfacestwo interfaces are independent and can evolve separatelycoupling is unforeseenadapts components after they have been designedbridge–––connects an abstraction and its many implementationsevolution is in accordance with the base abstractioncoupling between the abstraction and the implementations areknownWATERLOOCHERITON SCHOOL OFCOMPUTER SCIENCECS446/646 ECE45244
CS446/646 ECE452 3 WATERLOO CHERITON SCHOOL OF COMPUTER SCIENCE Motivation How can we improve OOD identify common characteristics - creation, structure, behaviour & interactions design patterns (design reuse) - generic blueprints (micro architecture) - language and implementation independent - two main catalogues GoF: Gang of Four (Gamma, Helm, Johnson, Vlissides, 1995)