Popular in Course
Popular in ComputerScienence
This 31 page Class Notes was uploaded by Vito Kilback on Wednesday September 23, 2015. The Class Notes belongs to CS350 at Drexel University taught by YuanfangCai in Fall. Since its upload, it has received 11 views. For similar materials see /class/212446/cs350-drexel-university in ComputerScienence at Drexel University.
Reviews for SoftwareDesign
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 09/23/15
1162008 Observer Pattern CSSSOSESIO Design Principles gt CouplingCohesionSeparation of Concern r OpenClose gt Dependency inversion gt Favor Composition over Inheritance gt Information Hiding Data Encapsulation Information Hiding in Patterns Which part is stable Which part varies The Factory Method pattern structure aracamymgimuu 7 An0plrlt1linn A Conmiupmnuu r 4FachyMelhodI r 7 mum micnncralei mriun Concrelecvealur The Factory Method pattern structure MW mar o Mummy 9 mmwm Q ConnnicFacmryz mm I o Amamm a ML I A I m I o WWW I A 1 I e 1162008 Builder Pattern 7 structure Decorator structure Strategy Pattern 7 structure mutant cmmwa curammume Pattern Language 1162008 Pattern Language gt Classi cation v Pattern context v Problem gt Consequences b RolesParticipants The Strategy pattern b Classi cation Behavioral purpose Class scope Pattern contextwhen you need to use different business rules or algorithms depending on the context oft e processing Problemalgorithm to be applied needs to be selected based on the data type or the client making the request gt Consequences De nes aiamily oi algorithms Gets rid ol switches or other condition ontro s MUST invoke all algorithms through the same interlace RolesParticipans Context Strategy Interface Concrete Strategies Observer Pattern Applicability gt When an abstraction has two aspects one depend on the other gt When a change to one object requires changing others and you don39t know how many objects need to be changed b When an object should be able to notify other objects without knowing who these objects are Observer Pattern Known Use r Smalltalk ModelViewControllerMVC User interface mework while Model is subject andView is observer gt Smalltalk ET and theTHINK class library provide the geneml Observer pattern v Otheruserinterface toolkits such as nterViewstheAndrew Toolkit and Unidraw 1162008 Observer Pattern Key features gt Intent De ne a onetomany dependency between objects so that when one object changes etate all its dependents are notified and updated automatically gt Problem v Solution Observers delegate the responsibility for monitoringlor an event to a enter object the Subject Observer Pattern Key features gt Participants and collaborators Subject knows its Observers because the Observers register with it 77 The Subject must notify the Observers when the event in uestion occurs q The Observers are responsible both for registering with the Subject and for getting the information from the Subject when notified Subjects and Observers gt Subject Publisher gt Observer Subscriber b The Subject must notify the Observers when an event occurs k The Observers are responsible both for registering with the Subject and for getting the information from the Subject when noti ed Callback model of PIS Observer pattern how it works gt Step I make the observers behave in the same way gt Step 2 have the observers register themselves gt Step 3 notifythe observers when event occurs 1162008 Observer pattern structure vmiacnun observer elatlilln Obsewer mum r5 rsubipmsmle lGatSl sH fUpdaa i l Observer pattern interactions aConcreteSublecl aConcreleObserver anotherConcreteObsener Observer pattern paIticipants gt Subject an interface Provides primitives for managing Observers Know all of its Observers Defines notify to send messages to all Observers gt ConcreteSubject Stores some state of interest Getter and setter methods for that state r Observer an interface Defines update to enable messages from Subjects gt ConcreteObserver Gets pinged via update and retrieves state changes Decisions to make gt Mapping subjects to their observers A collection in the ConcreteSublects7 OW l A l ltNoiilyl ouvaawu obsarvatsfau Decisions to make gt Who triggers the notification quot crunch n in answers a mle Who triggers the update gt Option I have all statesetting operations on concreteSubjects call the notify method after they change the subject s state The client making the state change doesn39t have to remember that Automatic contextual updates gt Option 2 make clients call notify at the right time Can wait to trigger the update Additional client responsibility Decisions to make gt Observing more than one subject updateSubject s abserv tSiam 5mm GelSla39Ell Decisions to make gt State propagation protocols i 1162008 Broadcasting State changes Decisions to make b Option l pull model t Specifying modi cations ofinterest explicitly The subject sends nothing butthe most minimal noti cation The observer ask for details explicitly thereafter Emphasizesthe subject39s ignorance of its observers 5 Option 2 push model The subject sends observers the details of the change The subject knows how the observers expect to receive its WWW I state changes i rNutilyil i Decisions to make Specifying modifications of b How do you encapsulate complex SubjectObserver interest explicitly relationships v Subject gt Example imagine atransactional change void attachObsener obs Aspect interest with setStateO operations spanning multiple Subjects gt Observer Observers to be noti ed only at the end of transaction t Must capture that specific logic void updateSubject subj Aspect interest What would you do 1162008 Variant ChangeManager Decisions Summary gt Mapping subjects to their observers gt Who trigger the notification gt Observer State Update D Observer Registration gt Who triggers the update gt Observing more than one subject b Specifying modifications of interest explicitly D Encapsulating complex update semantics Observer pattern h Classi cation Behavioral purpose Object scope gt Contextthen on need to maintain consistency between states of multiple separate objects without coupling them tightly gt Problesze ne onetomany loosely coupled dependencies between objects to automatically notify dependent objecs of state changes in object they depend upon gt Solution Publishsubscribemodel allows for loose coupling and automatic propagation of state from Subjects to Observers gt Consequenc Support for broadcast mode of communication Unexpected updates Java Support for the Observer Pattern gt Javau1 il Observer interface Observers observable class Subject 1162008 Constructor Summary hsexvahle u Construct an observable with zero Observers or that it has already mused all ofxts observers ofxts most recent Observe Interface Melhod Summary vmd object arm Ins method rs called Wheneverthe observed objectxs changed update observable e What if the interaction among objects are complex Mediator Colleague A 1162008 Mediator Benefits gt Increases the reusability of objects supported by the Mediator by decoupling them from the system gt Simpli es maintenance of the system by centralizing control logic 9 Simpli es and reduces the variety of messages sent between objects in the system Mediator Uses and Drawbacks b The Mediator is commonlyused to coordinate related GUI components gt A drawback of the Mediator pattern is that without proper design the Mediator object itself can become overly complex 1242008 Structural Patterns 2 What if there are too many instances Bridge Flyweight Proxy CSSSOSESIO F311 2003 Flyweight Pattern Flyweight Benefits gt Reduce the number of object instance at runtime saving memory F ywmmrmary o b Centralizes states for mam virtual objects into a single location unmaran 2m Jule w x 5m 0 mum mm Flyweight Uses and Drawbacks gt The Flyweight is used when a class has many instances and they can all be controlled identically t A drawback of the Flyweight pattern is that once you ve implemented it single logical instances of the class will not be able to behave independently from the other instances 1242008 What if both abstraction and the implementation will vary Motivation MSIconWindow Bridge Bndge i l i 3 x XDrawSiring 1242008 Bridge Pattern AA cuncmelmplemenwm Ouncreoelmulememora Consequences of using Bridge b Decouplinginterface and implementation may be con gured at runtime may even be changed El39 4 4 I gt r I W39 b Encourages layering resulting in better system gt Improved extensibility b Shields clients from implementation details Bridge Uses and Drawbacks D Useful in graphic and windowing systems that need to run over multiple platform b Useful any time you need to vary an interface and an implementation in different ways gt Increases complexity Participants D Absti39actionWindow I define the abstraction39s interface b maintains a reference to an object of type b lmplementor b Re ned Abstraction lconWindow DialogWindow b extends the interface de ned byAbstraction 1242008 Participants continue r lmplementorWindowlmp P defines an interface for implementation It cl assesTypically this lmplementor s Benefits gt Avoid permanent binding between an abstraction and its implementation gt Avoid nested generalizations r interface provides only primitive menthod l Ease adding new imPlEmentatiOnS r C 39 39 39 39 Y39y 39 39 39 Y39P gt Reduce code repetition b implements the lmplementor39s interface quot Allow mntlme SWltChlng of behaVlouquot D rawbacks r Double indirection Window operation are implemented by subclasses of Windowlmpl classWindow class must delegate the message to aWindowlmpl subclass which implements the appropriate med39rodThis will have a slight impact on performance Consequences r decouplinginterface amp implementation implementation of abstraction can be configured at runtime eliminate compile time dependencies on implementation encourages layering 9 improved extensibility Abstraction amp lmplementer can be extended independendy r hiding implementation details from clients 1242008 Bridge Vs Other Patterns gt Abstract Factory can create and configure a particular Bridge b Different from Adapter Pattern Adapter making unrelated classes work together usually applied to systems after redesign What if an Object shouldn t be accessed Bridge lets abstraction and implementation vary independently 9 used upfront in design dlreCtly39 Proxy Pattern Example using Proxy Pattern gt Provide a surrogate or placeholder for another object to control access to itquot AppCode RemoteObjectProxy Deals with communicationLogi 3 SET Caches static information quotquotquotquot quot39 lec k realSubjedgtReq uest 1242008 When to use Proxy Pattern 39 39 39 than a 39 r r needed gt Remote proxy provides local representative for object in different address space gt Virtual proxy creates expensive objects on demand gt Protection proxy controls access to original object gt Smart pointers are needed to manage object lifetime loading object into memory when rst referenced lock management for synchronization Consequences of using Proxy b Introduces a level of indirection in accessing objects I lndirection provides exibility b Incurred cost on additional object and computations Proxy Vs Other Patterns D Adapter changes interface Proxy provides the same interface protection proxy implements subset of interface may deny access to certain functions b Decorator adds functionality proxy controls functionality Words ofwisdorn gt 00 design principles gt So far The main goal almost not evident of design is to minimize coupling and maximize oh 390 esI n Identify the aspects of your application that vary and separate them from Program to an interface not an implementation Favor composition over inheritance The OpenClosed Principle Classes should be open for extension but closed for modi cation 1242008 How to start designing b What are the objects gt What are the responsibilities b What are going to change What will remain the same b What are the commonalities and what are the variations b Is there an applicable pattern quotso P Look at the pattern structure gt Figure out the classes that take the roles b Analyze ifthe pattern will help improving l maintainability 2 reusability Using design patterns Creational Patterns gt Abstract Factory I Builder b Factory Method b Prototype b Singleton Structural Patterns D Adapter I Bridge b Composite b Decorator b Facade b Flyweight b Proxy 1242008 Behavioral Patterns b Chain of Responsibility P Command b Interpreter b Iterator b Mediator b Memento b Observer gt State gt Strategy gt Template Method b Visitor HOW patterns help gt Single design patterns are useful as tactical design devices Reusable core of solution to specific design problem inthe smal gt Most patterns are designed to be easily combined Moving from inthesmall tomrds intheIarge b Example MVC MVC architectural pattern 3 patterns together Observer Composite Strategy Thinking in patterns gt Simple compositionof patterns do not provide you with a full design at most they give you a building block with wider scope and larger purpose which must be tted in the whole design gt What is the most natural way to inject patterns in your designer39s job a TiFquot process Thinking in patterns TiP D A process for leveraging design patterns gt Recognize pattern applicabilityin the problem domain b Order patterns in layers Provide incrementally Iefined context b Insert patterns one by one b Re ect on resulting design see if other patterns emerge gt Go back to 2 1242008 TiP pattern identification D First step possiblythe hardest Requires familiarity Demands experience D It39s an analysis activity D Considerthe problem domain and nd where patterns can apply Leverage the Context and Problem sections in the description of the pattern speci cation Don39t rush into the solution domain TiP ordering patterns D Recall patterns are solutions in context D Apply rst those pattems that can give context to other patterns D Layered approach Alexander calls it a process of complexification It39s actually a process of detail enrichment b Exam le Composite provides context in whichVisitor can be useful Not true the other way around Example D Imagine you have identi ed the following patterns as applicable Abstract Factory D What would be a natural order Builder need to create complex structure Abstract Factory enforces all elements of that structure to be of the same famil Prototype Abstract Factory can use prototypes objects to produce elements TiP insert pattern into design D Once the patterns are ordered use the rst one in the order D Two cases mature vs early design D Mature design eg refactoring will have to adapt patterns to existing classes start with the generic form ofthe pattern and map existing classes into it D Early design much less to adapt against more degree of freedom Perhaps the pattern becomes the cornerstone of the system 10152008 Economic Goal Lowerthe Cost of Maintenance Design Principles CouplingCohesinn OpenClnseJnlormation ng Dependency lnversianSeparatian nfConce Experiences of leveraging 00 to follow the principles Creational Patterns 2 csasosEalo m zoos OO programming Inheritance Encapsulation Polymorphism The Maintenance of Simple Maze Game What are the concerns b Is not Simple gt FeaturesConcems gt How the classes will be MazeType l Add redblueenlthzntedbombedHzrryPottenSnovWVhite Removed Each type requires a fzmilyquot 0 components Changed Maze Components mil door room maze Maze Structure Zrooms19 rooms I00 rooms Square maze Component Building many walls a room can have 439 839 How to build a door Maze Building Process Maxe ZRooms 3 Doors 10152008 Current code Simplification b We would like to factor out the knowledge about how to assemble Rooms b Solution Hire a contractor A Builder And just give orders Act as the Director of the work Meet the Builder Builder Pattern structure cnnmnu l l ConcmeBnllder EulluPan0 samesuuu 10152008 Builder Participants gt Builder speci es an abstract interface for creating parts of a Product object gt ConcreteBui constructs and assembles parts of the product by implementingthe Builder interface de nes and keeps trackof the representation it creates provides an interface for retrieving the product r Director demands the construction of an object using the Builder interface gt Product represents the comglex ob ect under constructionConcrete builder builds the product s internal representation and defines the process by which it is assembled Builder motivation gt The algorithm for creating a complex object should be independent of the parts that make up the object and how they re assembled gt The construction process must allow different representations for the object that s constructed The Maze with Builder gt Simplify the code of the CreateMaze method by passing it a MazeBuilder as a parameter gt MazeBuilder interface can be used to build three things the maze 2 rooms with a particular mom number 3 doors between numbered momsz The Maze Builder El MazeEmlder operations buiIdMaze i abstract buildRuum 1 bulldDUDr 1 Maze gerMaze uses ll SimpleMazaEmlder j attributes l Maze amecreator Dnevalioni attributes build l l huildRuum l ouerauons MD V Maze reareMaze mazeEuilder rhe Bulldevl 7 quot hui maze gerMazei 10152008 The Maze Bui1der gt The operations in the abstract MazeBuildersuper class are meant to be overridden by subclassesie concrete builders v Concrete builders will override also GetMaze t turn the Maze they build Modified code gt In the MazeGameCreator class Maze createMazeBuilder theBuilder builderbuidMaze builderbuiIdRoom1 builderbuildRoom2 builderbuidDoor12 return buildergetMaze The Maze Bui1der b Notice how the Builder hides the internal representation that is classes that de ne ro ms doors and walls ofthe maze how these parts are assembled to form the nal maze v This makes easy to change the way Maze is represente since no client code is dependent on it gt Forinstance we might have windows i t e representation of rooms This is a design decision that is hidden from clients gt Client only needs to know about Maze Rooms and oors in very little detail The Maze Bui1der v Subdividing responsibility between the Maze and Builder classes and separat39ngt etwo Enabled reusability oi part oi the tongrutiion gmtes Can have a variety oi MazeBuilders each constructing males with dillerent classes or roomswalls doors gt What was the basis for the decision which part ofthe construction remains in the MazeCreator and what is delegated to Builder Find what rnustvary and extract ithide it The varying partstype oi walls doors room e sta ie parts eg the iact that rooms are conn Th ilthis varies too vari es ected by doors What 10152008 What about sub contracting Do we still need A Factory The Maze Bui1der b The concrete builder SimpleMazeBuilder is an implementation that builds simple mazes b Let39s take a look at its code Maze myMaze Maze geiiviazeo remm myMaze void buildMaze myMaze new Maze void buildRoominti r n wR cm i myMazeaddRoomr all roomrconshuc on code SimpleMazeBuilder b This simple builder takes care of object instantiation itself i anilla rooms etc b We could still use a Factory For extensibili For separation of concerns gt Let39s create a FactoryMazeBuilder 10152008 F Q 13901 VMQ 7eR11ilrler 1 E MazEEullder auribules on mm buildM312 1 buildRuuml 1 1 1111mm 1 Maze gelMazei 1 usagevs 4 1 lgl SimpleMazaEullder Maze amecreamr almbules attributes a m quotS onevanons buxldMaze 1 Maze realeMaIEmazeEu1lder the Rudder bu1ldRuum 1 museum 1 E1 Maze geKMa e 1 Fworv mums nuerauons l3 FadoWMazeEmlder immanent 1 mm Fazmry vaazmry quot539 operations 5 uildMazelFazm H buildRuuml 1 buildDuur 1 Maze gelMaze 1 Builder Maze Game Creational patterns 1 Creational patterns involve object instantiation and all provide a way to decouple a client from objects it needs to instantiate gt Some members of this groupquot Factory Method Abstract Factory Bquer Intent 5 The intent of Factory Method is to allow a class to defer instantiation to its subclasses gt The intent ofAbstract Factory is to create families of related objects without explicitly tying the code on their concrete classes b The intent of Builder is to encapsulate the construction of composite structures 10152008 One of a Kind Objects gt There are cases in which you need one object of a certain type and only one Shared globally across the system b Examples More Creational patterns Abstraction for accessing a single resource eg log le A load balancer object A centralized Factory A dialog box that is used across the GUI Requirements b Enforce uniqueness sure nobody can create further instances use information hiding mechanisms t Responsibility on39t want the clients of that object to be responsible for checking uniqueness and for usage policy encapsulate that responsibility within the class of that object The Singleton pattern Multinthreadjng 10152008 mu up e hems ryto obtamthe Hmd eto no smg eton atthe sonnennnev umquenessguz mtee You need athreadszfe mp ementa onfor mu twrthreaded zpphmuons A bulletproof J ava idiom mm dais qu aan H vaate anst lutmv Suvwesses qenevamn or Duhht dam anst luctm Dvwahe qu aano o qu etanHa deHs aaded on the lstcaH or qu aan qeunstmceo avthe NS accessta qu aaandeleSWNCE nathefme quot Dvwahe Stan dais qu aanHa deN Duvets hna Stan S nq emn wsnwcz gt 2w squemno women qu etanqetlnslance vetum qu aanHa dev msrmcz gt Ihasmqlnlm Pa nnm nsu as a c ass has on uno mstancE and pmuosagmax pmmmacmssmm nu ma s nmekw Singleton msmme s a mute dais atmbute msmmeo s 2 a55 sum opemuon Creates and mawmams n5 own umque rsmme The Singleton pattern to have on one omea 012 dass but no g oba objeamntr o sth to ensure 2H he mnd eto 2H o y Soluuon gua v consequent Thzy an rm nun m pass nmund mums Clas ca on Crunmm pawns om I ContextYou mm e msmnuauon 0 Ms omeqvou mm ms reVererKe Ms omea wuzhout passmg 2 them m severa hens need regu ated 2ess to me same and you wantto ensure umqueness 39 rantees one and on on msmme es cm sao naznud m omnomxmnummums Msmgman mmquot Pattern team up gt Singleton Factory Method b How do they work together The product created by the Factory Method can be a Singleton A different type depending on settings or preferences Example javaawtTookit 10152008 Singleton variant gt Why one and only one gt What about N and no more than N gt Can you leverage the Singleton pattern to manage N objects that can be reused Think of thread or connection pools The Prototype pattern Creation vs cloning Creation is hard work We are better at cloning VS 10152008 Creation vs cloning b When you instantiate an object with the new operator you create it out of thin air eginJava the JVM goes through a complex process of loading memory allocation initialization b Cloning an existing object may be a better choice Especially when the object is complex andor large The two approaches Duuicdassshawl Uivate 5mm dns Public Shaw jWjamam VERV jam DNA Sm g Emil lass Shaw imdenmts CanEaHEl wmwemo Dublicstanc nal Shaw mm new saw Dvwate nal 5mm one My Public saw a Dwatevwlicattylllcmzol Mimommdmem Elwa Dbla gt gt gt gt Emil lass ShawdnnavladwinEl Long and memory expensive puuicsugnhcagmj 5521 Kit Donelorevery mam MM KEEN Shaw Utha mllv anEOy Java caveat shallow vs deep copy Prototype pattern D A prototype is an object that packs in advance all the necessary info for further instances t Instead of instantiating new instances clients clone the prototype gt Notice that cloning carries over the full w of the prototype Realworld usage D Exam les Object contains data that is complex to compute Object contains lots of data Object contains data that are loaded from a slow medium You want to give the same data to multiple workers 10152008 Prototype structure b We have done with all Creational Patterns 9 Let39s continue with Behavioral Patterns r The Command Pattern encapsulates a request as an object thereby letting you pai39ameterize clients with different requests queue or log requests and support undoable operations 10152008 Bullet Points t The Command Pattern deoouples an object making a request from the one that knows how to perform It s A Command object s at the center ofthls decoupling and encapsulates a recewer with an actlon n An Invoker makes a request ofa Command object by calling Its eteouteo method which Invoke those actions on the receivers 7 Bullet Points gt Invokers can he pammeterlxed with Commands even dynamically at runtlme V Commands may support undo by Implementing an undo method that restores the object to Its revlou state before the exeouteo method was last oaned
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'