《Design Patterns And Frameworks For Object-Oriented Communication Systems.pdf》由会员分享,可在线阅读,更多相关《Design Patterns And Frameworks For Object-Oriented Communication Systems.pdf(18页珍藏版)》请在三一文库上搜索。
1、DesignPatternsandFrameworks forObject?oriented CommunicationSystems DouglasC?Schmidt http?www?cs?wustl?edu?schmidt? schmidt?cs?wustl?edu WashingtonUniversity?St?Louis ? Motivation ?Developinge?cient?robust?extensible?and reusablecommunicationsoftwareishard ?Itisessentialtounderstandsuccessfultech? n
2、iquesthathaveprovene?ectivetosolve commondevelopmentchallenges ?Designpatternsandframeworkshelptocap? ture?articulate?andinstantiatethesesuc? cessfultechniques ? Observations ?Developersofcommunicationsoftwarecon? frontrecurringchallengesthatarelargely application?independent ?e?g?serviceinitializat
3、ionanddistribution?error handling?owcontrol?eventdemultiplexing?con? currencycontrol ?Successfuldevelopersresolvethesechallenges byapplyingappropriatedesignpatterns ?However?thesepatternshavetraditionally beeneither? ?Lockedinsideheadsofexpertdevelopers ?Buriedinsourcecode ? DesignPatterns ?Designpa
4、tternsrepresentsolutionstoprob? lemsthatarisewhendevelopingsoftware withinaparticularcontext ?i?e?Patterns?problem?solutionpairsinacon? text? ?Patternscapturethestaticanddynamicstruc? tureandcollaborationamongkeypartici? pantsinsoftwaredesigns ?Theyareparticularlyusefulforarticulatinghow andwhytores
5、olvenon?functionalforces ?Patternsfacilitatereuseofsuccessfulsoft? warearchitecturesanddesigns ? ProxyPattern NETWORK CLIENT SERVER : BROKER 1: METHOD CALL 4: METHOD RETURN : QUOTER 2: FORWARD REQUEST 3: RESPONSE : QUOTER PROXY ?Intent?provideasurrogateforanotherob? jectthatcontrolsaccesstoit ? Grap
6、hicalNotation PROCESS THREAD OBJECT : CLASS CLASS CLASS CATEGORY CLASS UTILITY INHERITS CONTAINS INSTANTIATES A ABSTRACT CLASS USES TEMPLATE CLASS ? MoreObservations ?Reuseofpatternsaloneisnotsu?cient ?Patternsenablereuseofarchitectureanddesign knowledge?butnotcode?directly? ?Tobeproductive?develope
7、rsmustalsoreuse detaileddesigns?algorithms?interfaces?im? plementations?etc? ?Applicationframeworksareane?ectiveway toachievebroadreuseofsoftware ? Frameworks ?Aframeworkis? ?Anintegratedcollectionofcomponentsthatcol? laboratetoproduceareusablearchitecturefora familyofrelatedapplications? ?Framework
8、sdi?erfromconventionalclass libraries? ?Frameworksare?semi?complete?applications ?Frameworksaddressaparticularapplicationdo? main ?Frameworksprovide?inversionofcontrol? ?Typically?applicationsaredevelopedbyin? heritingfromandinstantiatingframework components ? Di?erencesBetweenClass LibrariesandFram
9、eworks APPLICATION SPECIFIC LOGIC USER INTERFACE CLASS LIBRARIES NETWORKING MATH ADTS DATA BASE APPLICATION SPECIFIC LOGIC MATH OBJECT-ORIENTED FRAMEWORK ADTS INVOKES CALL BACKS NETWORKING USER INTERFACE DATABASE INVOKES EVENT LOOP EVENT LOOP ? TutorialOutline ?Outlinekeychallengesfordevelopingcom?
10、municationsoftware ?Presentthekeyreusabledesignpatternsin adistributedmedicalimagingsystem ?Bothsingle?threadedandmulti?threadedsolutions arepresented ?Discusslessonslearnedfromusingpatterns onproductionsoftwaresystems ? Stand?alonevs?Distributed ApplicationArchitectures PRINTER FILE SYSTEM PRINTER
11、FILE SYSTEM COMPUTER (1)(1) STAND-ALONESTAND-ALONE APPLICATIONAPPLICATION ARCHITECTUREARCHITECTURE (2)(2) DISTRIBUTEDDISTRIBUTED APPLICATIONAPPLICATION ARCHITECTUREARCHITECTURE CD ROM CD ROM NETWORK DISPLAY SERVICE FI LE SERVICE PRINT SERVICE CYCLE SERVICES ? Concurrencyvs?Parallelism CONCURRENT SER
12、VER maxfdp1 read_fds WORK REQUEST SERVER CLIENT WORK REQUEST WORK REQUEST WORK REQUEST CLIENT CLIENT CLIENT SERVER CPU1CPU2CPU3CPU4 WORK REQUEST WORK REQUEST WORK REQUEST WORK REQUEST CLIENT CLIENT CLIENT CLIENT PARALLEL SERVER ? SourcesofComplexity ?Distributedapplicationdevelopmentexhibits bothinh
13、erentandaccidentalcomplexity ?Inherentcomplexityresultsfromfundamen? talchallenges?e?g? ?Distributedsystems ?Latency ?Errorhandling ?Servicepartitioningandloadbalancing ?Concurrentsystems ?Raceconditions ?Deadlockavoidance ?Fairscheduling ?Performanceoptimizationandtuning ? SourcesofComplexity?cont?
14、d? ?Accidentalcomplexityresultsfromlimita? tionswithtoolsandtechniques?e?g? ?Low?leveltools ?e?g?Lackoftype?secure?portable?re?entrant? andextensiblesystemcallinterfacesandcom? ponentlibraries ?Inadequatedebuggingsupport ?Widespreaduseofalgorithmicdecomposition ?Fineforexplainingnetworkprogrammingco
15、n? ceptsandalgorithmsbutinadequatefordevel? opinglarge?scaledistributedapplications ?Continuousrediscoveryandreinventionofcorecon? ceptsandcomponents ? OOContributions ?Concurrentanddistributedprogramminghas traditionallybeenperformedusinglow?level OSmechanisms?e?g? ?fork?exec ?Sharedmemory ?Signals
16、 ?Socketsandselect ?POSIXpthreads?Solaristhreads?Win?threads ?OOdesignpatternsandframeworkselevate developmenttofocusonapplicationcon? cerns?e?g? ?Servicefunctionalityandpolicies ?Servicecon?guration ?Concurrenteventdemultiplexingandeventhan? dlerdispatching ?Serviceconcurrencyandsynchronization ? D
17、istributedMedicalImaging Example ?Thisexampleillustratesthereusabledesign patternsandframeworkcomponentsusedin anOOarchitectureforadistributedmedical imagingsystem ?ApplicationclientsusesBlobServerstostore andretrievemedicalimages ?ClientsandServerscommunicateviaaconnection? orientedtransportprotoco
18、l ?e?g?TCP?IP?IPX?SPX?TP? ? DistributedElectronicMedical ImagingArchitecture DIAGNOSTICDIAGNOSTIC STATIONSSTATIONS ATMATM MANMAN ATMATM LANLAN ATMATM LANLAN MODALITIESMODALITIES ( (CTCT, , MR MR, , CR CR) ) LOCALLOCAL STORESTORE MODALITIESMODALITIES ( (CTCT, , MR MR, , CR CR) ) NAMENAME SERVERSERVER
19、 ROUTINGROUTING SERVICESERVICE CENTRAL CENTRAL STORESTORE CLUSTERCLUSTER STORESTORE TIMETIME SERVERSERVER L LOCATIONOCATION SERSERVICEVICE ? ArchitectureoftheBlobServer : Reactor BLOBBLOB SERVERSERVER : Blob: Blob HandlerHandler svc_runsvc_runsvc_runsvc_run : Blob: Blob HandlerHandler : Blob: Blob H
20、andlerHandler : Blob: Blob AcceptorAcceptor : Options: Options svc_runsvc_run svc_runsvc_run : Blob: Blob ProcessorProcessor : Msg: Msg QueueQueue ?Manageshort?termandlong?termblobpersistence ?RespondtoqueriesfromBlobLocators ? DesignPatternsintheBlob Server Half-Sync/Half-Sync/ Half-AsyncHalf-Async
21、 StrategyStrategyAdapterAdapterProxyProxy TACTICAL PATTERNS STRATEGIC PATTERNS Double CheckedDouble Checked LockingLocking ConnectorConnector SingletonSingleton AcceptorAcceptor ServiceService ConfiguratorConfigurator ReactorReactor Thread-perThread-per RequestRequest Thread-perThread-per SessionSes
22、sion ThreadThread PoolPool Active ObjectActive Object ? TacticalPatterns ?Proxy ?Provideasurrogateorplaceholderforanother objecttocontrolaccesstoit? ?Strategy ?De?neafamilyofalgorithms?encapsulateeach one?andmaketheminterchangeable? ?Adapter ?Converttheinterfaceofaclassintoanotherin? terfaceclientex
23、pects? ?Singleton ?Ensureaclassonlyhasoneinstanceandprovide aglobalpointofaccesstoit? ? ConcurrencyPatterns ?Reactor ?Decoupleseventdemultiplexingandeventhan? dlerdispatchingfromapplicationservicesperformed inresponsetoevents? ?ActiveObject ?Decouplesmethodexecutionfrommethodinvo? cationandsimpli?es
24、synchronizedaccesstoshared resourcesbyconcurrentthreads? ?Half?Sync?Half?Async ?DecouplessynchronousI?Ofromasynchronous I?Oinasystemtosimplifyconcurrentprogram? minge?ortwithoutdegradingexecutione?ciency? ?Double?CheckedLockingPattern ?Ensuresatomicinitializationofobjectsandelim? inatesunnecessarylo
25、ckingoverheadoneachac? cess? ? ConcurrencyArchitecture Patterns ?Thread?per?Request ?Allowseachclientrequesttorunconcurrently? ?Thread?Pool ?AllowsuptoNrequeststoexecuteconcurrently? ?Thread?per?Session ?Allowseachclientsessiontorunconcurrently? ? ServiceInitializationPatterns ?Connector ?Decouplesa
26、ctiveconnectionestablishmentfrom theserviceperformedoncetheconnectionises? tablished? ?Acceptor ?Decouplespassiveconnectionestablishmentfrom theserviceperformedoncetheconnectionises? tablished? ?ServiceCon?gurator ?Decouplesthebehaviorofnetworkservicesfrom pointintimeatwhichservicesarecon?guredinto
27、anapplication? ? ConcurrencyPatternsintheBlob Server ?Thefollowingexampleillustratesthedesign patternsandframeworkcomponentsinan OOimplementationofaconcurrentBlob Server ?Therearevariousarchitecturalpatternsfor structuringconcurrencyinaBlobServer ?Reactive ?Thread?per?request ?Thread?per?session ?Th
28、read?pool ? ReactiveBlobServerArchitecture : Reactor: Reactor BLOB SERVERBLOB SERVER : Blob: Blob ProcessorProcessor : Blob: Blob AcceptorAcceptor SERVER CLIENT CLIENT CLIENT 1:1: CONNECT CONNECT 2:2: HANDLE INPUT HANDLE INPUT 3:3: CREATE PROCESSOR CREATE PROCESSOR 4:4: ACCEPT CONNECTION ACCEPT CONN
29、ECTION 5:5: ACTIVATE PROCESSOR ACTIVATE PROCESSOR 6:6: PROCESS BLOB REQUEST PROCESS BLOB REQUEST : Blob: Blob ProcessorProcessor ? Thread?per?RequestBlobServer Architecture SERVERSERVER CLIENTCLIENT CLIENTCLIENT CLIENTCLIENT : Reactor: Reactor BLOB SERVER : Blob: Blob AcceptorAcceptor 1:1: CONNECT C
30、ONNECT 2:2: HANDLE INPUT HANDLE INPUT 3:3: CREATE PROCESSOR CREATE PROCESSOR 4:4: ACCEPT CONNECTION ACCEPT CONNECTION 5:5: SPAWN THREAD SPAWN THREAD : Blob: Blob ProcessorProcessor : Blob: Blob ProcessorProcessor : Blob: Blob ProcessorProcessor 6:6: PROCESS BLOB REQUEST PROCESS BLOB REQUEST ? Thread
31、?per?SessionBlobServer Architecture SERVERSERVER CLIENTCLIENT CLIENTCLIENT 2:2: CREATE CREATE, , ACCEPT ACCEPT, , AND ACTIVATE AND ACTIVATE BLOB BLOB_ _PROCESSORPROCESSOR BLOB SERVER 1:1: BIND BIND CLIENTCLIENT : Blob: Blob ProcessorProcessor : Blob: Blob ProcessorProcessor : Blob: Blob ProcessorPro
32、cessor 4:4: PROCESS BLOB REQUEST PROCESS BLOB REQUEST 3:3: SPAWN THREAD SPAWN THREAD : Reactor: Reactor : Blob: Blob AcceptorAcceptor ? Thread?PoolBlobServer Architecture : Reactor: Reactor BLOB SERVERBLOB SERVER 1:1: BLOB BLOB REQUESTREQUEST 2:2: HANDLE INPUT HANDLE INPUT 3:3: ENQUEUE REQUEST ENQUE
33、UE REQUEST : Blob: Blob HandlerHandler 6:6: PROCESS BLOB REQUEST PROCESS BLOB REQUEST SERVERSERVER CLIENTCLIENT CLIENTCLIENT CLIENTCLIENT : Blob: Blob HandlerHandler : Blob: Blob HandlerHandler 5:5: DEQUEUE DEQUEUE select (handles); foreach h in handles foreach h in handles if (h is output handler)
34、if (h is output handler) tableh-handle_output () ; tableh-handle_output () ; if (h is input handler) if (h is input handler) tableh-handle_input (); tableh-handle_input (); if (h is signal handler) if (h is signal handler) tableh-handle_signal (); tableh-handle_signal (); this-expire_timers ();this-
35、expire_timers (); n n HandlesHandles 1 1 APPLICATIONAPPLICATION- - DEPENDENTDEPENDENT APPLICATION- INDEPENDENT n ?ParticipantsintheReactorpattern ? CollaborationintheReactor Pattern mainmain programprogram INITIALIZEINITIALIZE REGISTER HANDLERREGISTER HANDLER callback :callback : ConcreteConcrete Ev
36、ent_HandlerEvent_Handler START EVENT LOOPSTART EVENT LOOP DATA ARRIVESDATA ARRIVES OK TO SENDOK TO SEND reactorreactor : Reactor: Reactor handle_events() FOREACH EVENT DOFOREACH EVENT DO handle_input() select() Reactor() register_handler(callback) handle_output() SIGNAL ARRIVESSIGNAL ARRIVES TIMER E
37、XPIRESTIMER EXPIRES handle_signal() handle_timeout() get_handle() EXTRACT HANDLEEXTRACT HANDLE REMOVE HANDLERREMOVE HANDLER remove_handler(callback) INITIALIZATIONINITIALIZATION MODEMODE EVENT HANDLINGEVENT HANDLING MODEMODE handle_close() CLEANUPCLEANUP ? UsingtheReactorintheBlob Server : : Reactor
38、 Reactor REGISTERED OBJECTS : Handle: Handle TableTable FRAMEWORKFRAMEWORK LEVELLEVEL KERNELKERNEL LEVELLEVEL APPLICATIONAPPLICATION LEVELLEVEL OS EVENT DEMULTIPLEXING INTERFACEOS EVENT DEMULTIPLEXING INTERFACE 1: handle_input()1: handle_input() svc_runsvc_run svc_runsvc_run svc_runsvc_run : Blob: B
39、lob ProcessorProcessor : Message: Message QueueQueue 4: getq(msg)4: getq(msg) 5:svc(msg)5:svc(msg) : Event: Event HandlerHandler : Blob: Blob HandlerHandler : Event: Event HandlerHandler : Blob: Blob HandlerHandler : Event: Event HandlerHandler : Blob: Blob HandlerHandler 2: recv_request(msg)2: recv
40、_request(msg) 3: putq(msg)3: putq(msg) ? TheBlobHandlerInterface ?TheBlobHandleristheProxyforcommu? nicatingwithclients ?TogetherwithReactor?itimplementstheasyn? chronoustaskportionoftheHalf?Sync?Half?Async pattern ?ReusableSvcHandler? classBlob?Handler?publicEvent?Handler ? public? ?EntrypointintoB
41、lobHandler? virtualintopen?void? ?RegisterwithReactortohandleclientinput? Reactor?instance?register?handler ?this?READ?MASK? ? protected? ?NotifiedbyReactorwhenclientrequestsarrive? virtualinthandle?input?void? ?Receiveandframeclientrequests? intrecv?request?Message?Block? SOCK?Streampeer?stream?IPC
42、endpoint? ? ? TheActiveObjectPattern ?Intent ?Decouplesmethodexecutionfrommethodinvo? cationandsimpli?essynchronizedaccesstoshared resourcesbyconcurrentthreads? ?Thispatternresolvesthefollowingforces forconcurrentcommunicationsoftware? ?Howtoallowblockingreadandwriteoperations ononeendpointthatdonot
43、detractfromthequal? ityofserviceofotherendpoints ?Howtosimplifyconcurrentaccesstosharedstate ?Howtosimplifycompositionofindependentser? vices ? StructureoftheActiveObject Pattern ClientClient InterfaceInterface ResultHandle m1() ResultHandle m2() ResultHandle m3() ActivationActivation QueueQueue ins
44、ert() remove() SchedulerScheduler dispatch() m1() m2() m3() ResourceResource RepresentationRepresentation MethodMethod ObjectsObjects loop m = actQueue.remove() dispatch (m) INVISIBLEINVISIBLE TOTO CLIENTSCLIENTS VISIBLEVISIBLE TOTO CLIENTSCLIENTS n n 1 1 1 1 1 1 1 1 1 1 ?TheSchedulerdeterminesthese
45、quencethat MethodObjectsareexecuted ? CollaborationintheActive ObjectPattern INVOKEINVOKE INSERT ININSERT IN PRIORITY QUEUE PRIORITY QUEUE cons(m1) remove(m1)DEQUEUE NEXTDEQUEUE NEXT METHOD OBJECT METHOD OBJECT RETURN RESULTRETURN RESULT EXECUTEEXECUTE clientclient : Client: Client InterfaceInterfac
46、e : Activation: Activation QueueQueue insert(m1) dispatch(m1) METHOD OBJECTMETHOD OBJECT CONSTRUCTIONCONSTRUCTION SCHEDULING/ EXECUTION COMPLETION m1() : Represent-: Represent- ationation : Scheduler: Scheduler CREATE METHOD OBJECT reply_to_future() future() RETURN RESULTRETURN RESULT HANDLEHANDLE ?
47、 UsingtheActiveObjectPattern intheBlobServer : : Reactor Reactor : Handle: Handle TableTable FRAMEWORKFRAMEWORK LEVELLEVEL KERNELKERNEL LEVELLEVEL APPLICATIONAPPLICATION LEVELLEVEL 1: handle_input()1: handle_input() REGISTERED OBJECTS : Event: Event HandlerHandler : Blob: Blob HandlerHandler svc_run
48、svc_run svc_runsvc_run svc_runsvc_run 4: getq(msg)4: getq(msg) 5:svc(msg)5:svc(msg) : Event: Event HandlerHandler : Blob: Blob HandlerHandler : Event: Event HandlerHandler : Blob: Blob HandlerHandler 2: recv_request(msg)2: recv_request(msg) 3: putq(msg)3: putq(msg) : Blob: Blob ProcessorProcessor :
49、Message: Message QueueQueue OS EVENT DEMULTIPLEXING INTERFACEOS EVENT DEMULTIPLEXING INTERFACE ? TheBlobProcessorClass ?ProcessesBlobrequestsusingthe?Thread? Pool?concurrencymodel ?Implementthesynchronoustaskportionofthe Half?Sync?Half?Asyncpattern classBlob?Processor?publicTask? public? ?Singletonaccesspoint? staticBlob?Processor?instance?void? ?Passarequesttothethreadpool? virtualput?Message?Block? ?Eventloopforthepoolthread virtualintsvc