• No results found

Using Design Patterns to Develop Object-Oriented Communication Software Frameworks and Applications Douglas C. Schmidt http:www.cs.wustl.edu

N/A
N/A
Protected

Academic year: 2021

Share "Using Design Patterns to Develop Object-Oriented Communication Software Frameworks and Applications Douglas C. Schmidt http:www.cs.wustl.edu"

Copied!
16
0
0

Loading.... (view fulltext now)

Full text

(1)

Using Design Patterns to Develop Object-Oriented Communication

Software Frameworks and Applications

Douglas C. Schmidt

http://www.cs.wustl.edu/



schmidt/

[email protected]

Washington University, St. Louis

1

Motivation



Developing ecient, robust, extensible, and reusable communication software is hard



It is essential to understand successful tech- niques that have proven e ective to solve common development challenges



Design patterns and frameworks help to cap- ture, articulate, and instantiate these suc- cessful techniques

2

Observations



Developers of communication software con- front recurring challenges that are largely application-independent

{

e.g., service initialization and distribution, error handling, ow control, event demultiplexing, con- currency control



Successful developers resolve these challenges by applying appropriate design patterns



These patterns have traditionally been ei- ther:

1. Locked inside the heads of expert software devel- opers 2. Buried within the source code

Design Patterns



Design patterns represent solutions to prob- lems that arise when developing software within a particular context

{

i.e., \Patterns text"

==

problem/solution pairs in a con-



Patterns capture the static and dynamic struc- ture and collaboration among key partici- pants in software designs

{

They are particularly useful for articulating how and why to resolve non-functional forces



Patterns facilitate reuse of successful soft-

ware architectures and designs

(2)

Proxy Pattern

NETWORK

CLIENT

SERVER : BROKER

1: METHOD CALL

4: METHOD RETURN

: QUOTER

2: FORWARD REQUEST

3: RESPONSE

: QUOTER PROXY



Indent: provide a surrogate for another ob- ject that controls access to it

5

More Observations



Reuse of patterns alone is not insucient

{

Patterns enable reuse of architecture and design knowledge, but not code (directly)



To be productive, developers must also reuse detailed designs, algorithms, interfaces, im- plementations, etc.



Application frameworks are an e ective way to achieve broad reuse of software

6

Frameworks



A framework is:

{

\An integrated collection of components that col- laborate to produce a reusable architecture for a family of related applications"



Frameworks di er from conventional class libraries:

1. Frameworks are \semi-complete" applications 2. Frameworks address a particular application do- main 3. Frameworks provide \inversion of control"



Typically, applications are developed by in- heriting from and instantiating framework components

Di erences Between Class Libraries and Frameworks

APPLICATION SPECIFIC

LOGIC

USER INTERFACE

CLASS LIBRARIES

NETWORKING

MATH

ADT

S

DATA BASE

APPLICATION SPECIFIC

LOGIC MATH

OBJECT - ORIENTED FRAMEWORK ADT

S

INVOKES

CALL BACKS

NETWORKING USER

INTERFACE

DATABASE INVOKES

EVENT LOOP

EVENT LOOP

(3)

Tutorial Outline



Outline key challenges for developing com- munication software



Present the key reusable design patterns in an application-level Gateway

{

Both single-threaded and multi-threaded solutions are presented



Discuss lessons learned from using patterns on production software systems

9

Stand-alone vs. Distributed Application Architectures

PRINTER

SYSTEMFILE

PRINTER 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

10

Concurrency vs. Parallelism

CONCURRENT SERVER

maxfdp1 read_fds

WORK REQUEST

SERVER

CLIENT

WORK

REQUEST WORK

REQUEST

WORK REQUEST CLIENT

CLIENT CLIENT

SERVER

CPU1 CPU2 CPU3 CPU4

WORK REQUEST

WORK

REQUEST WORK

REQUEST

WORK REQUEST CLIENT

CLIENT

CLIENT CLIENT

PARALLEL SERVER

Sources of Complexity



Distributed application development exhibits both inherent and accidental complexity



Inherent complexity results from fundamen- tal challenges, e.g.,

{

Distributed systems

.

Latency

.

Error handling

.

Service partitioning and load balancing

{

Concurrent systems

.

Race conditions

.

Deadlock avoidance

.

Fair scheduling

.

Performance optimization and tuning

(4)

Sources of Complexity (cont'd)



Accidental complexity results from limita- tions with tools and techniques, e.g.,

{

Lack of type-secure, portable, re-entrant, and ex- tensible system call interfaces and component li- braries

{

Inadequate debugging support

{

Widespread use of algorithmic decomposition

.

Fine for explaining network programming con- cepts and algorithms but inadequate for devel- oping large-scale distributed applications

13

OO Contributions



Concurrent and distributed programming has traditionally been performed using low-level OS mechanisms, e.g.,

{

fork/exec

{

Shared memory

{

Signals

{

Sockets and select

{

POSIX pthreads, Solaris threads, Win32 threads



OO design patterns and frameworks elevate development to focus on application con- cerns, e.g.,

{

Service functionality and policies

{

Service con guration

{

Concurrent event demultiplexing and event han- dler dispatching

{

Service concurrency and synchronization

14

Application-level Gateway Example



This example illustrates the reusable design patterns and framework components used in an OO architecture for application-level Gateways



Gateways route messages between Peers in a distributed system



Peers and Gateways communicate via a connection- oriented transport protocol

{

e.g., TCP/IP, IPX/SPX, TP4

Physical Architecture of the Gateway

WIDE AREA NETWORK

SATELLITES

TRACKING STATION

PEERS

STATUS INFO

COMMANDS

BULK DATA TRANSFER

LOCAL AREA NETWORK

GATEWAY

GROUND

STATION

PEERS

(5)

OO Software Architecture of the Gateway

: Reactor

GATEWAY

PEER2 PEER3 PEER4

CONNECTION REQUEST

CONNECTION REQUEST

OUTGOING MESSAGES : Output

Channel

INCOMING MESSAGES

: Channel Acceptor : Channel

Connector

PEER1 : Input Channel

: Routing

Table : Input

Channel

: Output Channel

17

Graphical Notation

PROCESS

THREAD

OBJECT

: CLASS

CLASS

CLASS CATEGORY

CLASS UTILITY

INHERITS

CONTAINS

INSTANTIATES

A

ABSTRACT CLASS

USES TEMPLATE

CLASS

18

Gateway Behavior



Components in the Gateway behave as fol- lows:

1. Gateway Peers to connect with and which routes to use parses con guration les that specify which 2. Channel Connector connects to Peers, then cre-

ates and activates the appropriate Channel sub- classes ( Input Channel or Output Channel ) 3. Once connected, Peers send messages to the Gate- way

{

Messages are handled by the appropriate Input Channel

{

Input Channels work as follows:

(a) Receive and validate messages (b) Consult a Routing Table

(c) Forward messages to the appropriate Peer(s) via Output Channel s

Design Patterns in the Gateway

Active Object Active Object

Half-Sync/

Half-Sync/

Half-Async Half-Async

Factory Factory Method Method Iterator

Iterator Template Template Adapter Adapter Method

Method

TACTICAL

TACTICAL PATTERNS PATTERNS STRATEGIC

PATTERNS

Connector

Connector Acceptor Acceptor Router

Router

Service Service Configurator Configurator

Reactor Reactor



The Gateway components are based upon

a family of design patterns

(6)

Tactical Patterns



Iterator

{

\Provide a way to access the elements of an ag- gregate object sequentially without exposing its underlying representation"



Factory Method

{

\De ne an interface for creating an object, but let subclasses decide which class to instantiate"

.

Factory Method lets a class defer instantiation to subclasses



Adapter

{

\Convert the interface of a class into another in- terface client expects"

.

Adapter lets classes work together that couldn't otherwise because of incompatible interfaces

21

Concurrency Patterns



Reactor

{

\Decouples event demultiplexing and event han- dler dispatching from application services performed in response to events"



Active Object

{

\Decouples method execution from method invo- cation and simpli es synchronized access to shared resources by concurrent threads"



Half-Sync/Half-Async

{

\Decouples synchronous I/O from asynchronous I/O in a system to simplify concurrent program- ming e ort without degrading execution eciency"

22

Service Initialization Patterns



Connector

{

\Decouples active connection establishment from the service performed once the connection is es- tablished"



Acceptor

{

\Decouples passive connection establishment from the service performed once the connection is es- tablished"



Service Con gurator

{

\Decouples the behavior of network services from point in time at which services are con gured into an application"

Application-Speci c Patterns



Router

{

\Decouples multiple sources of input from multiple sources of output to route data correctly without blocking"

(7)

The ADAPTIVE Communication Environment (ACE)

THREAD LIBRARY SYNCH SYNCH WRAPPERS WRAPPERS

COMMUNICATION COMMUNICATION SUBSYSTEM SUBSYSTEM

VIRTUAL MEMORY VIRTUAL MEMORY SUBSYSTEM SUBSYSTEM DYNAMIC DYNAMIC LINKING LINKING

MEMORY MEMORY MAPPING MAPPING SELECT

SELECT//

POLL POLL

SYSTEM SYSTEM V V IPCIPC STREAM

STREAM PIPES PIPES

NAMED NAMED PIPES PIPES

SYSV SYSV WRAPPERS WRAPPERS SPIPE

SAP

GENERAL UNIX AND WIN32 SERVICES C

APIC APISS

C++

C++

WRAPPERS WRAPPERS FRAMEWORKS

AND CLASS CATEGORIES

THREAD MANAGER

PROCESS/THREAD SUBSYSTEM

SOCKETS/ TLI

MEM MAP SHARED MALLOC ACCEPTOR CONNECTOR

DISTRIBUTED

SERVICES NAME

SERVER TOKEN

SERVER

LOGGING SERVER GATEWAY

SERVER

SOCK_SAP/ TLI_SAP

FIFO SAP

REACTOR LOG MSG

SERVICE CONFIG- URATOR ADAPTIVE SERVICE EXECUTIVE

(ASX)

SERVICE HANDLER

CORBA HANDLER



A set of C++ wrappers and frameworks based on common design patterns

25

ACE Components in the Gateway

GATEWAY GATEWAY CONNECTION

CONNECTION REQUEST

REQUEST CONNECTION

REQUEST

OUTGOING MESSAGES : Output

: Output Channel Channel

: Message : Message Queue Queue : SOCK : SOCK Stream Stream

INCOMING MESSAGES

: Acceptor : Acceptor

: SOCK : SOCK Acceptor Acceptor

: Connector : Connector

: SOCK : SOCK Connector Connector : Map: Map

Manager Manager

: Input : Input Channel Channel

: SOCK : SOCK Stream Stream

: Routing : Routing Table Table

: Map : Map Manager Manager

: Output : Output Channel Channel

: Message : Message Queue Queue : SOCK : SOCK Stream Stream

: Input : Input Channel Channel

: SOCK : SOCK Stream Stream

: Reactor : Reactor

PEERS PEERS

26

The Reactor Pattern



Intent

{

\Decouples event demultiplexing and event han- dler dispatching from the services performed in re- sponse to events"



This pattern resolves the following forces for event-driven software:

{

How to demultiplex multiple types of events from multiple sources of events eciently within a single thread of control

{

How to extend application behavior without requir- ing changes to the event dispatching framework

Structure of the Reactor Pattern

Reactor Reactor

handle_events() register_handler(h) remove_handler(h) expire_timers()

11 11

11

Event_Handler Event_Handler

handle_input() handle_output() handle_signal() handle_timeout() get_handle()

A 11

nn

nn Concrete Concrete Event_Handler Event_Handler

Timer_Queue Timer_Queue

schedule_timer(h) cancel_timer(h) expire_timer(h)

11

11 select (handles);

select (handles);

foreach h in handles { foreach h in handles { if (h is output handler) if (h is output handler) table[h]->handle_output () ; table[h]->handle_output () ; if (h is input handler) if (h is input handler) table[h]->handle_input ();

table[h]->handle_input ();

if (h is signal handler) if (h is signal handler) table[h]->handle_signal ();

table[h]->handle_signal ();

}}this->expire_timers ();

this->expire_timers ();

nn Handles Handles

11

APPLICATION APPLICATION -- DEPENDENT DEPENDENT APPLICATION

- INDEPENDENT

n



Participants in the Reactor pattern

(8)

Collaboration in the Reactor Pattern

program main

INITIALIZE REGISTER HANDLER

callback : Concrete Event_Handler

START EVENT LOOP

DATA ARRIVES OK TO SEND

reactor : Reactor

handle_events()

FOREACH EVENT DO

handle_input() select() Reactor() register_handler(callback)

handle_output()

SIGNAL ARRIVES TIMER EXPIRES

handle_signal() handle_timeout()

get_handle()

EXTRACT HANDLE

REMOVE HANDLER

remove_handler(callback)

INITIALIZATION MODEEVENT HANDLING MODE

handle_close()

CLEANUP

29

Using the Reactor for the Gateway

:: Reactor Reactor

REGISTERED REGISTERED OBJECTS OBJECTS

FRAMEWORKFRAMEWORK LEVELLEVELKERNELKERNEL LEVELLEVELAPPLICATIONAPPLICATION LEVELLEVEL

OS EVENT DEMULTIPLEXING INTERFACE

:Timer :Timer Queue

Queue : Signal: Signal

Handlers Handlers : Handle

: Handle Table Table : Event

: Event Handler Handler : Output : Output Channel Channel

: Event : Event Handler Handler : Output : Output Channel Channel

: Event : Event Handler Handler : Input : Input Channel Channel

1: handle_input() 1: handle_input() 4: send(msg)

4: send(msg)

2: recv(msg) 2: recv(msg) 3: route(msg) 3: route(msg)

30

The Router Pattern



Intent

{

\Decouple multiple sources of input from multiple sources of output to route data correctly without blocking"



The Router pattern resolves the following forces for connection-oriented routers:

{

How to prevent misbehaving connections from dis- rupting the quality of service for well-behaved con- nections

{

How to allow di erent concurrency strategies for Input and Output Channels

Structure of the Router Pattern

Routing Routing Table Table

find()

Output Output Channel Channel

send_msg() put()

Input Input Channel Channel

recv_msg()

1

nn

I/OI/O LAYERLAYER ROUTINGROUTING LAYERLAYER

Message Message Queue Queue

EVENT SOURCE AND SINK EVENT SOURCE AND SINK



Participants in the Router pattern

(9)

Collaboration in the Router Pattern

: Routing : Routing Table Table

recv_msg() find ()

I/O LayerI/O Layer : Input

: Input Channel Channel

FIND DESTINATIONS FIND DESTINATIONS ROUTE MSG ROUTE MSG

main() main()

SEND MSG SEND MSG

((QUEUE IF FLOWQUEUE IF FLOW CONTROLLED CONTROLLED))

put()

wakeup()

FLOW CONTROL FLOW CONTROL

ABATES ABATES DEQUEUE AND SEND DEQUEUE AND SEND MSG

MSG ((REQUEUE IFREQUEUE IF FLOW CONTROLLED FLOW CONTROLLED))

: Output : Output Channel Channel

RECV MSG RECV MSG

send_msg() INPUT PROCESSING PHASE

ROUTE SELECTION PHASE

OUTPUT PROCESSING PHASE

dequeue() enqueue()

send_msg()

schedule_wakeup()

33

Structure of the Single-Threaded Router Pattern

Routing Routing Table Table

find()

Output Output Channel Channel

handle_output() put()

Input Input Channel Channel

handle_input()

1

nn

Reactor Reactor nn 11

Event Event Handler Handler

REACTIVEREACTIVE LAYERLAYER ROUTINGROUTING LAYERLAYER

Message Message Queue Queue

34

Collaboration in Single-threaded Gateway Routing

: Routing : Routing Table Table

: Input : Input Channel Channel

7: put (msg) 7: put (msg)

1: handle_input() 1: handle_input() 2: recv_peer(msg) 2: recv_peer(msg) 3: find()

3: find()

:: MessageMessage Queue Queue

: Output : Output Channel Channel

5: send_peer(msg) 5: send_peer(msg)

ROUTE ROUTE ID

ID SubscriberSubscriber Set Set

4: put (msg) 4: put (msg)

::

MessageMessage Queue Queue

: Output : Output Channel Channel

8: send_peer(msg) 8: send_peer(msg) 9: enqueue(msg) 9: enqueue(msg) 10: schedule_wakeup() 10: schedule_wakeup() ---

--- 11: handle_output() 11: handle_output() 12: dequeue(msg) 12: dequeue(msg) 13: send_peer(msg) 13: send_peer(msg)

The Active Object Pattern



Intent

{

\Decouples method execution from method invo- cation and simpli es synchronized access to shared resources by concurrent threads"



This pattern resolves the following forces for concurrent communication software:

{

How to allow blocking read and write operations on one endpoint that do not detract from the qual- ity of service of other endpoints

{

How to simplify concurrent access to shared state

(10)

Structure of the Active Object Pattern

Client Client Interface Interface

ResultHandle m1() ResultHandle m2() ResultHandle m3()

Activation Activation Queue Queue

insert() remove()

Scheduler Scheduler

dispatch() m1'() m2'() m3'()

Resource Resource Representation

Representation Method Method Objects Objects

loop {

m = actQueue.remove() dispatch (m)

}

INVISIBLE INVISIBLE

TO CLIENTSTO CLIENTS VISIBLE VISIBLE

TO CLIENTSTO CLIENTS

nn

11

11 11

11 11



The Scheduler is a \meta-object" that de- termines the sequence Method Objects are executed

37

Collaboration in the Active Object Pattern

INVOKE INVOKE

INSERT IN INSERT IN PRIORITY QUEUE PRIORITY QUEUE

cons(m1')

remove(m1')

DEQUEUE NEXT DEQUEUE NEXT METHOD OBJECT METHOD OBJECT

RETURN RESULT RETURN RESULT

EXECUTE EXECUTE

client

client : Client: Client Interface

Interface : Activation: Activation Queue Queue

insert(m1')

dispatch(m1')

METHOD OBJECTMETHOD OBJECT CONSTRUCTIONCONSTRUCTIONSCHEDULING/ EXECUTIONCOMPLETION

m1()

: Represent- : Represent-

ation ation : Scheduler

: Scheduler

CREATE METHOD OBJECT

reply_to_future() future()

RETURN RESULT RETURN RESULT

HANDLE HANDLE

38

Using the Active Object Pattern for the Gateway

:: Reactor Reactor

REGISTERED OBJECTS

FRAMEWORKFRAMEWORK LEVELLEVELKERNELKERNEL LEVELLEVELAPPLICATIONAPPLICATION LEVELLEVEL

OS EVENT DEMULTIPLEXING INTERFACE

:Timer :Timer Queue

Queue : Signal: Signal

Handlers Handlers : Handle

: Handle Table Table : Event

: Event Handler Handler : Output : Output Channel Channel

: Event : Event Handler Handler : Input : Input Channel Channel

: Event : Event Handler Handler : Input : Input Channel Channel

: Event : Event Handler Handler : Input : Input Channel Channel

1: handle_input() 1: handle_input() : Event

: Event Handler Handler : Output : Output Channel Channel

4: send(msg) 4: send(msg)

2: recv(msg) 2: recv(msg) 3: route(msg) 3: route(msg)

Collaboration in the Active Object-based Gateway Routing

: Routing Table

: Input

Channel

:MessageQueue

: Output Channel 4: put (msg)

1: handle_input () 2: recv_peer(msg) 3: find()

:Message Queue

: Output Channel

5: send_peer(msg)

5: send_peer(msg)

ACTIVE

ACTIVE ROUTE

ID Subscriber

Set

(11)

Half-Sync/Half-Async Pattern



Intent

{

\Decouples synchronous I/O from asynchronous I/O in a system to simplify programming e ort without degrading execution eciency"



This pattern resolves the following forces for concurrent communication systems:

{

How to simplify programming for higher-level com- munication tasks

.

These are performed synchronously

{

How to ensure ecient lower-level I/O communi- cation tasks

.

These are performed asynchronously

41

Structure of the

Half-Sync/Half-Async Pattern

QUEUEINGQUEUEING LAYERLAYER ASYNCHRONOUSASYNCHRONOUS TASK LAYER TASK LAYER SYNCHRONOUSSYNCHRONOUS TASK LAYER TASK LAYER

S

YNC TASK

1

SS

YNCYNC

TASK TASK

33

SS

YNCYNC TASK TASK

22 1, 4: read(data)

1, 4: read(data)

3: enqueue(data) 3: enqueue(data)

2: interrupt 2: interrupt

ASYNC ASYNC TASK TASK

EXTERNAL EXTERNAL EVENT SOURCES EVENT SOURCES MESSAGE QUEUES MESSAGE QUEUES

42

Collaborations in the Half-Sync/Half-Async Pattern

EXTERNAL EVENT

PROCESS MSG

read(msg)

EXECUTE TASK ENQUEUE MSG

External

Event Source Async

Task Sync

Message Task Queue

enqueue(msg) work()

DEQUEUE MSG

ASYNC PHASEQUEUEING PHASESYNC PHASE

RECV MSG

notification()

read(msg) work()



This illustrates input processing (output pro- cessing is similar)

Using the Half-Sync/Half-Async Pattern in the Gateway

QUEUEINGQUEUEING LAYERLAYER ASYNCHRONOUSASYNCHRONOUS TASK LAYER TASK LAYER SYNCHRONOUSSYNCHRONOUS TASK LAYER TASK LAYER 1: dequeue(msg) 1: dequeue(msg) 2: send(msg) 2: send(msg)

: Output : Output Channel Channel

2: recv(msg) 2: recv(msg) 3: get_route(msg) 3: get_route(msg) 4: enqueue(msg) 4: enqueue(msg)

1: dispatch() 1: dispatch() : Reactor : Reactor

MESSAGE QUEUES MESSAGE QUEUES

: Input : Input Channel Channel : Input : Input

Channel Channel

: Input : Input Channel Channel

: Output : Output Channel Channel : Output

: Output

Channel

Channel

(12)

The Connector Pattern



Intent

{

\Decouples active initialization of a service from the task performed once a service is initialized"



This pattern resolves the following forces for network clients that use interfaces like sockets or TLI:

1. How to reuse active connection establishment code for each new service 2. How to make the connection establishment code portable across platforms that may contain sock- ets but not TLI, or vice versa

3. How to enable exible service concurrency policies 4. How to actively establish connections with large number of peers eciently

45

Structure of the Connector Pattern

Reactor Reactor nn

11

Event Event Handler Handler

Connector Connector

connect_svc_handler() activate_svc_handler() handle_output() connect(sh, addr)

SVC_HANDLER SVC_HANDLER PEER_CONNECTOR PEER_CONNECTOR

Concrete Concrete Connector Connector

Concrete_Svc_Handler Concrete_Svc_Handler SOCK_Connector SOCK_Connector

Concrete

11

Concrete Svc Handler Svc Handler

SOCK Stream SOCK Stream

open()

nn

REACTIVEREACTIVE LAYERLAYERCONNECTIONCONNECTION LAYERLAYERAPPLICATIONAPPLICATION LAYERLAYER

handle_output()

A A

connect_svc_handler connect_svc_handler (sh, addr);

(sh, addr);

1:

1:

Svc Handler Svc Handler

PEER_STREAM PEER_STREAM

open() AA

INITS

activate_svc_handler activate_svc_handler (sh);

(sh);

2:

2:

nn

46

Collaboration in the Connector Pattern

Client

FOREACH CONNECTION INITIATE CONNECTION SYNC CONNECT

INSERT IN REACTOR

con : Connector

handle_input() reactor : Reactor Svc_Handlersh:

register_handler(sh) get_handle() EXTRACT HANDLE

DATA ARRIVES

svc() PROCESS DATA

connect(sh, addr)

connect() ACTIVATE OBJECT

: SOCK Connector

SERVICE PROCESSING PHASE

activate_svc_handler(sh) connect_svc_handler(sh, addr)

CONNECTION INITIATION/ SEVICE INITIALIZATION

PHASE

START EVENT LOOP FOREACH EVENT DO

handle_events() select() open()



Synchronous mode

Collaboration in the Connector Pattern

Client

FOREACH CONNECTION INITIATE CONNECTION ASYNC CONNECT INSERT IN REACTOR

START EVENT LOOP FOREACH EVENT DO

handle_events() select() CONNECTION COMPLETE

INSERT IN REACTOR

con : Connector

handle_input() reactor :

Reactor Svc_Handlersh:

handle_event()

register_handler(sh) get_handle() EXTRACT HANDLE

DATA ARRIVES

svc() PROCESS DATA

connect(sh, addr) connect()

ACTIVATE OBJECT

register_handler(con) : SOCK

Connector

CONNECTION INITIATION

PHASE

SERVICE INITIALIZATION PHASE

SERVICE PROCESSING PHASE

activate_svc_handler(sh) connect_svc_handler(sh, addr)

open()



Asynchronous mode

(13)

Using the Connector for the Gateway

: Connector

: Reactor

PENDING CONNECTIONS

ACTIVE CONNECTIONS

: Svc Handler : Channel

: Svc Handler : Channel : Svc

Handler : Channel : Svc Handler : Channel

: Svc Handler : Channel

: Svc Handler : Channel : Svc

Handler : Channel

49

The Acceptor Pattern



Intent

{

\Decouples passive initialization of a service from the tasks performed once the service is initialized"



This pattern resolves the following forces for network servers using interfaces like sock- ets or TLI:

1. How to reuse passive connection establishment code for each new service 2. How to make the connection establishment code portable across platforms that may contain sock- ets but not TLI, or vice versa

3. How to ensure that a passive-mode descriptor is not accidentally used to read or write data 4. How to enable exible policies for creation, con- nection establishent, and concurrency

50

Structure of the Acceptor Pattern

Reactor Reactor

11

Acceptor Acceptor

SVC_HANDLER SVC_HANDLER PEER_ACCEPTOR PEER_ACCEPTOR

Concrete Concrete Acceptor Acceptor

Concrete_Svc_Handler Concrete_Svc_Handler SOCK_Acceptor SOCK_Acceptor

Concrete

11

Concrete Svc Handler Svc Handler

SOCK Stream SOCK Stream

open()

nn

REACTIVEREACTIVE LAYERLAYERCONNECTIONCONNECTION LAYERLAYERAPPLICATIONAPPLICATION LAYERLAYER

INITS INITS

Svc Handler Svc Handler

PEER_STREAM PEER_STREAM

open() A A

sh = make_svc_handler();

sh = make_svc_handler();

accept_svc_handler (sh);

accept_svc_handler (sh);

activate_svc_handler (sh);

activate_svc_handler (sh);

nn Event Event Handler Handler

handle_input()

A A

make_svc_handler() accept_svc_handler() activate_svc_handler() open()

handle_input()

Collaboration in the Acceptor Pattern

Server

REGISTER HANDLER

START EVENT LOOP

CONNECTION EVENT

REGISTER HANDLER FOR CLIENT I/O

FOREACH EVENT DO EXTRACT HANDLE INITIALIZE PASSIVE

ENDPOINT

acc : Acceptor

handle_input() handle_close()

reactor : Reactor

select() Svc_Handlersh:

handle_input()

register_handler(sh) get_handle()

EXTRACT HANDLE DATA EVENT

CLIENT SHUTDOWN

svc()

PROCESS MSG

open()

CREATE, ACCEPT,

AND ACTIVATE OBJECT

SERVER SHUTDOWN handle_close()

ENDPOINT INITIALIZATION PHASE

SERVICE INITIALIZATION PHASE

SERVICE PROCESSING PHASE

: SOCK Acceptor

handle_events() get_handle() register_handler(acc)

sh = make_svc_handler() accept_svc_handler (sh) activate_svc_handler (sh)

open()



Acceptor is a factory that creates, connects,

and activates a Svc Handler

(14)

Using the Acceptor Pattern in the Gateway

: Input : Input Acceptor Acceptor

:: Reactor Reactor

ACTIVE CONNECTIONS

: Svc Handler : Input : Input Channel Channel

: Svc : Svc Handler Handler : Output : Output Channel Channel

: Svc : Svc Handler Handler : Output : Output Channel Channel

: Svc : Svc Handler Handler : Input : Input Channel Channel

PASSIVE LISTENERS

: Output : Output Acceptor Acceptor

53

The Service Con gurator Pattern



Intent

{

\Decouples the behavior of network services from the point in time at which these services are con- gured into an application"



This pattern resolves the following forces for highly exible communication software:

{

How to defer the selection of a particular type, or a particular implementation, of a service until very late in the design cycle

.

i.e., at installation-time or run-time

{

How to build complete applications by composing multiple independently developed services

{

How to recon gure and control the behavior of the service at run-time

54

Structure of the Service Con gurator Pattern

Reactor Reactor nn

11

Event Event Handler Handler

Concrete Concrete Service Object Service Object

REACTIVEREACTIVE LAYERLAYERCONFIGURATIONCONFIGURATION LAYERLAYERAPPLICATIONAPPLICATION LAYERLAYER

11

11

Service Service Config Config

nn Service Service Object Object

A suspend() suspend() resume() resume() init() init() fini() fini() info() info()

11

Service Service Repository Repository

11

Collaboration in the Service Con gurator Pattern

: Service : Service Config Config main()

main()

REGISTER SERVICE REGISTER SERVICE

START EVENT LOOP START EVENT LOOP INCOMING EVENT INCOMING EVENT FOREACH EVENT DO FOREACH EVENT DO

STORE IN REPOSITORY STORE IN REPOSITORY CONFIGURE

CONFIGURE

FOREACH SVC ENTRY DO FOREACH SVC ENTRY DO

svc : svc : Service_Object

Service_Object : Reactor: Reactor

run_event_loop()

handle_events() handle_input()

Service_Config()

: Service : Service Repository Repository

insert()

EXTRACT HANDLE EXTRACT HANDLE INITIALIZE SERVICE

INITIALIZE SERVICE init(argc, argv)

fini()

DYNAMICALLY LINK DYNAMICALLY LINK

SERVICE

SERVICE link_service()

unlink_service()

SHUTDOWN EVENT

SHUTDOWN EVENT handle_close()

UNLINK SERVICE UNLINK SERVICE

remove() register_handler(svc)

get_handle()

remove_handler(svc) CONFIGURATIONCONFIGURATION MODEMODEEVENT HANDLING MODE

process_directives()

CLOSE SERVICE CLOSE SERVICE

(15)

Using the Service Con gurator Pattern for the Gateway

: Service Config

SERVICE CONFIGURATOR

RUNTIME

: Service Repository

: Reactor : Service Object : Reactive

Gateway

: Service Object : Thread Pool Gateway

SHARED OBJECTS

: Service Object : Thread Gateway



Replace the single-threaded Gateway with a multi-threaded Gateway

57

Bene ts of Design Patterns



Design patterns enable large-scale reuse of software architectures



Patterns explicitly capture expert knowledge and design tradeo s



Patterns help improve developer communi- cation



Patterns help ease the transition to object- oriented technology

58

Drawbacks to Design Patterns



Patterns do not lead to direct code reuse



Patterns are deceptively simple



Teams may su er from pattern overload



Patterns are validated by experience rather than by testing



Integrating patterns into a software devel- opment process is a human-intensive activ- ity

Suggestions for Using Patterns E ectively



Do not recast everything as a pattern

{

Instead, develop strategic domain patterns and reuse existing tactical patterns



Institutionalize rewards for developing pat- terns



Directly involve pattern authors with appli- cation developers and domain experts



Clearly document when patterns apply and do not apply



Manage expectations carefully

(16)

Books and Magazines on Patterns



Books

{

Gamma et al., \Design Patterns: Elements of Reusable Object-Oriented Software" Addison-Wesley, Reading, MA, 1994.

{

\Pattern Languages of Program Design," editors James O. Coplien and Douglas C. Schmidt, Addison- Wesley, Reading, MA, 1995



Special Issues in Journals

{

\Theory and Practice of Object Systems" (guest editor: Stephen P. Berczuk)

{

\Communications of the ACM" (guest editors: Dou- glas C. Schmidt, Ralph Johnson, and Mohamed Fayad)



Magazines

{

C++ Report and Journal of Object-Oriented Pro- gramming, columns by Coplien, Vlissides, and De Souza

61

Conferences and Workshops on Patterns



Joint Pattern Languages of Programs Con- ferences

{

3rd PLoP

.

September 4

,

6, 1996, Monticello, Illinois, USA

{

1st EuroPLoP

.

July 10

,

14, 1996, Kloster Irsee, Germany

{

http://www.cs.wustl.edu/

~

schmidt/jointPLoP

,

96.html/



USENIX COOTS

{

June 17

,

21, 1996, Toronto, Canada

{

http://www.cs.wustl.edu/

~

schmidt/COOTS

,

96.html/

62

Obtaining ACE



The ADAPTIVE Communication Environ- ment (ACE) is an OO toolkit designed ac- cording to key network programming pat- terns



All source code for ACE is freely available

{

Anonymously ftp to wuarchive.wustl.edu

{

Transfer the les /languages/c++/ACE/*.gz and

gnu/ACE-documentation/*.gz



Mailing lists

* [email protected]

* [email protected]

* [email protected]

* [email protected]



WWW URL

{

http://www.cs.wustl.edu/

~

schmidt/

References

Related documents