Upload
emerald-golden
View
212
Download
0
Tags:
Embed Size (px)
Citation preview
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 1
SE 1
Patterns@Work
Frank BuschmannSiemens AG, Corporate Technology
Dept. Software & Engineering
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 2
SE 1
Patterns
Patterns help building high-quality software systems by
• presenting a concrete solution schema for recurring design problems;
• documenting proven design experience;
• specifying concepts above the level of individual classes and objects;
• describing structure and behavior of cooperating objects;
• providing a common vocabulary and concept understanding;
• addressing specific quality properties of the problem’s solution; and
• covering all ranges of scale and abstraction.
Half Object Plus Protocol(by Gerard Meszaros)
Problem: Performance-efficient implemen-tation of objects which are needed in twodistant address spaces.Solution: Divide the objects into two halfs,one in each address space, with a protocolbetween them. Local services are executedlocally, thus gaining performance.Distributed services are coordinated via theprotocol. Their consistency is guaranteed.
local
remote
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 3
SE 1
Patterns and Systems
However ...
every pattern addresses a single problem only, without considering other related or
dependent problems.
Building complex systems, in contrast, means to deal with many problems, which
also depend on each other.
A catalog of isolated patterns or even a pattern system thus helps locally, but does
not support a holistic approach to constructing software systems with patterns.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 4
SE 1
Pattern-based Software Architecture
A conflict?
If a pattern catalog or a pattern system does not support constructing software
systems with patterns as desired ....
... how then can patterns help building high-quality software systems
at all?
Proxy
DBMS
Proxy Broker
Bridge
Proxy*
** 0..1
View Controller
Client
CommunicationInfrastructure
UserInterface
FunctionalCore
Model
Persistence
1
11
1
1 1
Gotcha!
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 5
SE 1
Let’s look overan architect’sshoulder
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 6
SE 1
The Domain
Warehouse Management Systems
• organize warehouse operation: storing, fetching, commissioning, replenishment, etc.
• control process automation.
• keep books of items stored in the warehouse.
• cooperate with other software systems, such as PPS, Database, etc.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 7
SE 1
Challenges
Key Challenges in Building a Warehouse Management System
• specifying the base-line architecture.
• specifying the inter-process communication mechanisms.
• designing the warehouse core.
• specifying the warehouse core interface.
• designing the database connection.
• designing the user interface.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 8
SE 1
Base-line Architecture
The Base-line Architecture
Requirements analysis reveals 4 factors that impact the system’s basic architecture:
• Distribution. The system is highly distributed across a computer network.
• Human-computer interaction. Users communicate with the application using a huge variety of interfaces.
• Platform independence. The system must run in a heterogeneous environment.
• Component Integration. We want to integrate 3rd party products, such as databases, and legacy software.
Proxy
DBMS
Proxy Broker
Bridge
Proxy*
** 0..1
View Controller
Client
CommunicationInfrastructure
UserInterface
FunctionalCore
Model
Persistence
1
11
1
1 1
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 9
SE 1
Communication Infrastructure
Problem
A warehouse management system is highly distributed across a computer network. Its
software architecture must:
• Provide a communication infrastructure.
• Support location transparency of components.
• Hide platform and component specifics from application components.
• Allow for integration of legacy software.
UNIX Server Windows NTClients
BasicAutomation
The System
Equipment
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 10
SE 1
Communication Infrastructure
Solution
Provide a communication infrastructure for the warehouse management system with the
Broker pattern:
• The broker component is the system’s central request and data router and hides platform specifics.
• Bridges enable communication between different brokers.
• Client-side and server-side proxies represent components of the system in remote address spaces and shield clients from broker specifics.
• Clients (e.g., Commissioning Client) and servers (Warehouse Core) represent application components.
CommunicationInfrastructure
Application Components
Proxy
CommissioningClient
Broker
BridgeWarehouse
Core
*
** 0..1
Proxy
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 11
SE 1
User Interface
Problem
Users communicate with the application using a huge variety of interfaces: handheld terminals, form-based interfaces, command-line interfaces, and event-driven interfaces:
• All interfaces operate on the same functional core, which thus should be independent of interface-specifics.
• Interfaces may change over time, for example from command-line interfaces to event driven-interfaces.
The System
Equipment
Commissioning
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 12
SE 1
User Interface
Solution
Separate the user interface of the warehouse management system from its functional core
with the Model-View-Controller pattern:
• A model (WarehouseCore) represents the application’s functionality.
• Views (e.g., Commissioning Client) represent application data and information in an interface-specific way.
• Controllers (e.g., Commissioning) allow to control the application in an interface-specific way.
Proxy Broker
BridgeWarehouse
Core
*
**
0..1
CommissioningControllers
CommissioningViews
Commissioning Client
Proxy
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 13
SE 1
Communication
Problem
The system must provide a location transparent inter-process communication
mechanism using low-level operating system features:
• Different services needed for the location transparent IPC differ in their abstraction level.
• Self-contained parts of the IPC logic should be exchangeable.
• Code changes in one part of the IPC logic should not ripple through the whole system.
Logic foo
a b
xy
foo’
Communication method call
method dispatch
connection management
OS access
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 14
SE 1
Persistence
Solution
Separate the broker component into different parts by applying the
Layers pattern:
• An Interface Layer provides access to the broker component.
• An Adapter Layer implements the dispatching of remotely called services on the system’s objects.
• A Communication Layer implements connection handling and event dispatching.
• An OS Layer abstracts from low-level operating system APIs.
Proxy
BridgeWarehouse
Core
*
**
0..1
CommissioningControllers
CommissioningViews
Commissioning Client
ProxyInterface
Adapter
Communi-cation
OS
Broker
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 15
SE 1
Legacy And 3rd Party Component Integration
Problem
The warehouse management system must support the integration of legacy code, such
as for basic process automation, and 3rd
party components, such as DBMS:
• Interfaces of components providing the same functionality may vary vendor dependent.
• Component interfaces may not match with
the application’s view on the functionality they offer.Interface of
Database A
foo
a b
xy
foo’ foo
a b
xy
foo’
Interface ofDatabase B
Application viewon Databases
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 16
SE 1
Legacy And 3rd Party Component Integration
Solution
Integrate legacy and 3rd party components by using the Adapter pattern:
• A client (WarehouseCore) represents the user of the component.
• Adaptees (DBMS, BasicAutomation) represents the components to be integrated.
• Adapters (DBMS-Adapter, BA-Adapter) map between client interfaces and the adaptees’ interfaces.
Proxy
DBMS
DBMSAdapter
Proxy
BasicAutomation
BAAdapter
Proxy
BridgeWarehouse
Core
*
**
0..1
CommissioningControllers
CommissioningViews
Commissioning Client
ProxyInterface
Adapter
Communi-cation
OS
Broker
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 17
SE 1
Summary (1)
4 Patterns define the Base-line Architecture
• Broker defines the fundamental communication infrastructure.
• Model-View-Controller helps keeping the functional core independent of customer-specific user interfaces.
• Layers separates the functional core from communication aspects.
• Adapter supports the integration of legacy and pre-fabricated 3rd party components.
Proxy
DBMS
DBMSAdapter
Proxy
BasicAutomation
BAAdapter
Proxy
BridgeWarehouse
Core
*
**
0..1
CommissioningControllers
CommissioningViews
Commissioning Client
ProxyInterface
Adapter
Communi-cation
OS
Broker
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 18
SE 1
Summary (2)
The Result
A ‘classical’ 3-tier architecture for distributed systems.
‘Known Uses’ @ Siemens
• Warehouse Management
• Hot Rolling Mill Automation
• Medical Imaging
• Network Management
• ComUnity
Middleware
UNIX-ServerNT-ServerThin Client
Adapter Adapter Adapter
User Interface
DBMS
PersistencyBusiness Logic
ObjectObject
Object
Logic
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 19
SE 1
Communication Infrastructure
The Communication Infrastructure
4 factors characterize the communication infrastructure:
• Heterogeneous computing environment.
• Efficient inter-process communication.
• Location transparency of components.
• Plug ‘n’ Play environment.
Proxy
DBMS
Proxy Broker
Bridge
Proxy*
** 0..1
View Controller
Client
CommunicationInfrastructure
UserInterface
FunctionalCore
Model
Persistence
1
11
1
1 1
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 20
SE 1
The Basic Concept (1)
Broker Provides the Concept
The Broker pattern provides the conceptual principles on which the communication
infrastructure relies.
CORBA compliant Object Request Brokers, such as IONA Orbix, Inprise Visibroker and Sun Cool, Microsoft’s DCOM, and the Java
RMI all follow the Broker pattern.
We do not need to build our own communication infrastructure, but to use an existing product most effectively, we need
to know its key design principles.
CommunicationInfrastructure
Application Components
Proxy
Commissioning
Broker
BridgeWarehouse
Core
*
** 0..1
Proxy
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 21
SE 1
The Basic Concept (2)
Layers Provides the Abstraction
The Layers pattern divides the communication functionality into different parts of different purpose and abstraction.
CORBA compliant Object Request Brokers all follow the Layers pattern:
• The Interface Layer corresponds to the ORB Interface.
• The Adapter Layer corresponds to the Portable Object Adapter.
• The Communication Layer corresponds to the ORB Core.
Proxy
BridgeWarehouse
Core
*
** 0..1
CommissioningClient
ProxyInterface
Adapter
Communi-cation
OS
BrokerOur Focus
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 22
SE 1
Accessing OS APIs
Problem
Developing communication software is hard if developers must wrestle with low-
level-system APIs.
• OS APIs differ from platform to platform.
• OS dependencies in system code.
• Mismatch between procedural programming style of OS APIs and the object paradigm used in the warehouse management application.
#if defined (_WIN32) static CRITICAL_SECTION lock;#else static mutex_t lock;#endif /* _WIN32 */...// Handle UNIX/Win32 portability// differences.#if defined (_WIN32) SOCKET h; DWORD t_id;#else int h; thread_t t_id;#endif /* _WIN32 */...#if defined (_WIN32) ThreadCreate( ... );#else thr_create( ... );#endif /* _WIN32 */
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 23
SE 1
Accessing OS APIs
Solution
Hide dependencies to the operating system via the Wrapper Facade pattern.
• Wrapper Facades (e.g., ThreadManager, Sockets) provide a uniform object-oriented access to low-level operating system services.
• Functions (thr_create(), ThreadCreate()) are the operating system functions needed to implement the communication software.
• Clients (Communication) use the wrapper facades to get access to operating system services.
Telegram Office
Warehouse Core Server
Commis-sioning
A Client
ThreadManager
SOCKET
Operating System
SELECT
Communication
ThreadManager
SOCKET
Operating System
SELECT
Communication
TelegramOfficeStub
TelegramOfficeSkeleton
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 24
SE 1
Accessing OS APIs
class Thread_Manager {public: // Creates a new thread. static int spawn (THR_FUNC func, void *args = 0, long flags = THR_NEW_LWP, thread_t *t_id = 0, hthread_t *t_handle = 0, long priority = DEFAULT_THREAD_PRIORITY, int grp_id = -1, void *stack = 0, size_t stack_size = 0);
// Join a thread specified by <tid>. static int join (ACE_thread_t tid, void **status = 0);
// Suspend and resume a single thread. int suspend (thread_t); int resume (thread_t);
// Many more functions ...};
class SOCK_Stream {public: // Constructor. SOCK_Stream(void) : handle_(INVALID_HANDLE_VALUE) {};
// Initialize from an existing HANDLE. SOCK_Stream(SOCKET h) : handle_(h) {};
// Close the handle on destruction. ~ SOCK_Stream(void) { close(handle_); };
// Set and get. void set_handle(SOCKET h) { handle_ = h; };
SOCKET get_handle (void) const { return handle; };
// I/O operations. int recv(char* buf, size_t len,
int flags = 0); int send(const char* buf, size_t len,
int flags = 0);private: SOCKET handle_;};
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 25
SE 1
Inter-Process Communication
Problem
We need to implement the GIOP on top of a specific inter-process communication
mechanism.
• Different platforms provide different IPC mechanisms.
• The IPC mechanism to be used may change over time.
• Stubs and Skeletons know where the components they represent are located and to be invoked, but they are unaware of the platform’s IPC mechanisms.
Peer 1
Peer 2
GIOP processing
Here
There
Request
Request
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 26
SE 1
Inter-Process Communication
Solution
Encapsulate the GIOP processing into objects with the
Forwarder-Receiver pattern:
• Peers (Commissioning, TelegramOffice inclusive its stub and skeleton) represent components that want to communicate.
• A forwarder (ConnectionHandler on the client-side) is responsible for forwarding requests to a remote peer using a specific GIOP implementation.
• A receiver (ConnectionHandler on the server-side) is responsible for receiving a GIOP request and calling the addressed peer to process the request.
ThreadManager
SOCKET
Operating System
SELECT
Warehouse Core Server
Commis-sioning
A Client
Telegram Office
TelegramOfficeStub
TelegramOfficeSkeleton
request/responseConnection
HandlerConnection
Handler
ThreadManager
SOCKET
Operating System
SELECT
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 27
SE 1
Inter-Process Communication
class Client_Connection_Handler : public Service_Handler {public: Client_Connection_Handler (Thread_Manager *t = 0); virtual Client_Connection_Handler ();
// <Connector> hook. virtual int open (void *);
// Activation template method. virtual int send_request (ORB_Core* orb_core, OutputCDR &stream, int is_twoway);
// Event Handler overloads. virtual int handle_input (HANDLE); virtual int handle_close (HANDLE, Reactor_Mask);
// Perform appropriate closing. virtual int close (u_long flags = 0);protected: // ...};
class Server_Connection_Handler : public Service_Handler {public: Server_Connection_Handler (Thread_Manager *t = 0); virtual Server_Connection_Handler ();
// <Acceptor> hook. virtual int open (void *);
// Activation template method. virtual int activate (/* many parameters */);
// Called when the handler is turned // into an active object virtual int svc (void);
// Message processing. virtual int handle_message (InputCDR &msg, OutputCDR &response, bool &response_required, long &request_id, Environment &_env);protected: // ...};
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 28
SE 1
Event Demultiplexing
Problem
Incoming events from remote clients must be demultiplexed onto the corresponding
object and method.
• Different platforms provide different event demultiplexing mechanisms.
• Event demultiplexing should be decoupled
from subsequent event handling.select() WaitForMultipleObjects()
Event
Dispatch
Object1
service1
Object2
service2
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 29
SE 1
Event Demultiplexing
Solution
Decouple the general event demultiplexing and service provider dispatching from
service-specific event processing with the Reactor pattern:
• An event demultiplexer (SELECT) is a Wrapper Facade which blocks awaiting events to occur.
• An initiation dispatcher (Reactor) provides a general mechanism for dispatching events to service providers.
• Event handlers (ConnectionHandler, TelegramOfficeSkeleton, Telegram- Office) are responsible for application- specific service processing.
ThreadManager
SOCKET
Operating System
SELECT
Warehouse Core Server
Commis-sioning
A Client
Telegram Office
TelegramOfficeStub
TelegramOfficeSkeleton
request/responseConnection
HandlerConnection
Handler
ThreadManager
SOCKET
Operating System
SELECT
Reactor
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 30
SE 1
Event Demultiplexing
int Select_Reactor::handle_events() (Time_Value *max_wait_time) { int result = -1;
SEH_TRY { Select_Reactor_Handle_Set
dispatch_set; int number_of_active_handles = this->wait_for_multiple_events (dispatch_set, max_wait_time);
result = this->dispatch (number_of_active_handles, dispatch_set); };
SEH_EXCEPT (this->release_token ()) { // As it stands now, we catch and // then rethrow all Win32 structured // exceptions so that we can make // sure to release the <token_> // lock correctly. };
return result;}
int Select_Reactor::dispatch (int number_of_active_handles, dispatching &dispatch_set) { do { // Keep track of changes to our state. state_changed_ = 0
// Dispatch timers first. if (dispatch_timer_handlers () == -1) // State has changed. break;
// Dispatch notification handlers. else if (dispatch_notification_handlers (...) == -1) // State has changed. break;
// Dispatch I/O handlers. else
if (this->dispatch_io_handlers (...) == -1) // State has changed. break; } while (number_of_active_handles > 0);
return 1;}
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 31
SE 1
Connection Establishment
Problem
Before peers in a distributed system can communicate, a connection between them
must be established.
• Adding new peers should not affect existing connection establishment code.
• Connection roles of peers should be decoupled from their communication roles.
• Connection strategies change much less frequently than service implementations.Peer 1
Peer 2
The Network
Connect me to Peer 2, please.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 32
SE 1
Connection Establishment
Solution
Separate connection establishment from service processing with the Acceptor-Connector pattern:
• Event handlers (ConnectionHandlers, are responsible for GIOP processing.
• An acceptor passively accepts connection requests from remote peers.
• A connector actively initiates connections to remote service handlers.
• A dispatcher (Reactor) is responsible for routing connection requests.Thread
ManagerSOCKET
Operating System
SELECT
Reactor
Warehouse Core Server
Commis-sioning
A Client
Telegram Office
TelegramOfficeStub
TelegramOfficeSkeleton
request/response
Connector Acceptor
ConnectionHandler
ConnectionHandler
connect
createcreate
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 33
SE 1
Connection Establishment
template <class HANDLER, class PEER_ACCEPTOR> int Acceptor<HANDLER, PEER_ACCEPTOR>::accept () {
// Create a new HANDLER. HANDLER *handler = make_handler ();
// Accept connection from client. accept_handler (handler);
// Activate HANDLER by calling // its open() hook. activate_handler (handler);}
template <class HANDLER, class PEER_ACCEPTOR> class Acceptor : public Event_Handler { public: // Initialize transport enpoint. virtual int open (const PEER_ACCEPTOR::PEER_ADDR &local_addr, Concurrency_Strategy<HANDLER> *s);
// Factory Method that creates, connects, // and activates HANDLER's. virtual int accept ();
protected: // Handler creation, connection. and // concurrency strategies. virtual HANDLER* make_handler (void); virtual int accept_handler (HANDLER *); virtual int activate_handler (HANDLER *);
// Handling connection requests. virtual int handle_event (HANDLE, EVENT);
private: HANDLER* handler; PEER_ACCEPTOR peer_acceptor_; Concurrency_Strategy<HANDLER> *con_s;};
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 34
SE 1
Concurrency
Problem
We like to support concurrency.
• Different platforms provide different threading libraries.
• Whether or not we use concurrency, and if
so, the use of a particular concurrency mechanism, should be transparent to other components in the communication software.
Request
Object
RequestDispatch
Object
A Thread
Another Thread
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 35
SE 1
Concurrency
Solution
Transparently support concurrency with the Active Object pattern:
• A proxy (TelegramOfficeStub) receives client requests and forwards them (via the ConnectionHandler) to the Active Object.
• A scheduler (Reactor) receives requests from the proxy and dispatches them on the servant when they become runnable.
• An activation queue (SOCKET::socket queue) maintains pending method requests for the scheduler.
• A servant (ConnectionHandler, TelegramOfficeSkeleton, Telegram- Office) processes the requested service.
ThreadManager
SOCKET
Operating System
SELECT
Reactor
Warehouse Core Server
Commis-sioning
A Client
Telegram Office
TelegramOfficeStub
TelegramOfficeSkeleton
request/response
Connector Acceptor
ConnectionHandler
ConnectionHandler
connect
createcreate
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 36
SE 1
Concurrency
int Task_Base::activate (/* many params */) { // If the task passed in is zero, we will // use <this>. if (task == 0) task = this;
if (thr_count_ > 0 && force_active == 0) return 1; // Already active. else thr_count_ += n_threads;
// Use the Thread_Manager singleton if // the caller didn't supply us // with a Thread_Manager. if (thr_mgr_ == 0) thr_mgr_ = Thread_Manager::instance ();
if (thread_names == 0) // thread names were not specified grp_id_ = thr_mgr_->spawn_n(/* ... */); else // thread names were specified grp_id_ = thr_mgr_->spawn_n(/* ... */);
if (grp_id_ == -1) return -1; else return 0;}
template <class HANDLER> int Concurrency_Strategy<HANDLER>:: activate_handler (HANDLER *handler, void *arg) {
// Call up to our parent to do the // HANDLER initialization. if (inherited::activate_handler (handler, arg) == -1) return -1; else // Turn the <handler> into an // active object (if it isn't already // one as a result of the first // activation...) return handler->activate (thr_flags_, n_threads_);}
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 37
SE 1
Concurrency Strategies
Problem
There are different concurrency strategies.
• The component which spawns new threads, the Acceptor, should not depend on a particular concurrency strategy.
• Without breaking existing code, the system should be extensible with new concurrency strategies.
Object
RequestDispatch
A Thread
Thread per RequestThread per Connection
Thread Pool
Request
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 38
SE 1
Concurrency Strategies
Solution
Support multiple concurrency strategies with the Strategy pattern:
• A context (Acceptor) uses a particular concurrency strategy to create threads for
running Active Objects.
• An abstract strategy (Concurrency- Strategy) provides a common interface for all specific concurrency strategies.
• Concrete strategies (ThreadPer- Connection) implement a particular concurrency strategy.
ThreadManager
SOCKET
Operating System
SELECT
Reactor
Warehouse Core Server
Commis-sioning
A Client
Telegram Office
TelegramOfficeStub
TelegramOfficeSkeleton
request/response
Connector Acceptor
ConnectionHandler
ConnectionHandler
connect
create
ConcurrencyStrategy
ThreadPerConnection
create
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 39
SE 1
Initialization (1)
Problem
There are many different strategies for different purposes in the communication software.
• Not all of these strategies can be combined in a semantically consistent manner, since some mutually exclude themselves.
• The configuration of the system with a consistent set of strategies should be easy.
Interface
Adapter
Communi-cation
OS
Broker
ProtocolProtocol
DemuxStrategy
DemuxStrategy
ConcurrencyStrategy
ConcurrencyStrategy
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 40
SE 1
ThreadManager
SOCKET
Operating System
SELECT
Reactor
Warehouse Core Server
Telegram Office
TelegramOfficeSkeleton
Acceptor
ConnectionHandlercreate
ConcurrencyStrategy
ThreadPerConnection
Initialization (1)
Solution
Configure the communication infrastructure with semantically consistent strategies via
the Abstract Factory pattern:
• An abstract factory provides a generic interface for configuring the communication software with strategies.• Concrete factories (QuelleFactory) implement the configuration of the system with a semantically consistent set of concrete strategies for a specific customer.• Products (ThreadPerConnection) are the strategies with which concrete factories can configure the system.
AbstractFactory
QuelleFactory
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 41
SE 1
Initialization (2)
Problem
It may be necessary to re-configure the communication software with different
strategies.
However, we cannot afford any downtime of the system.
Interface
Adapter
Communi-cation
OS
Broker
Protocol1
DemuxStrategy1
ConcurrencyStrategy1
Factory1
Protocol2
DemuxStrategy2
ConcurrencyStrategy2
Factory2
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 42
SE 1
Initialization (2)
SolutionSupport run-time (re-)configuration of the
communication infrastructure with the Service Configurator pattern:
• A service (AbstractFactory) defines a common interface for configuring and executing a particular factory.
• Concrete services (QuelleFactory) are factories that configure a particular set of strategies with the system.
• A service repository maintains the currently configured and loaded factories.
• A service configurator can dynamically load factories to, and unload from, the service repository, and execute them.
ThreadManager
SOCKET
Operating System
SELECT
Reactor
Warehouse Core Server
Telegram Office
TelegramOfficeSkeleton
Acceptor
ConnectionHandlercreate
ConcurrencyStrategy
ThreadPerConnection
AbstractFactory
QuelleFactory
ServiceRepository
ServiceConfigurator
*
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 43
SE 1
Summary (1)
8 Patterns Define the Communication Layer
• Wrapper Facade shields it from the OS.
• Forwarder-Receiver encapsulates the IPC.
• Reactor performs general event dispatching.
• Acceptor-Connector supports connection establishment.
• Active Object supports concurrency.
• Strategy supports different communication layer personalities.
• Abstract Factory helps configuring a concrete personality.
• Service Configurator supports a run-time (re-) configuration of these personalities.
ThreadManager
SOCKET
Operating System
SELECT
Reactor
Warehouse Core Server
Commis-sioning
A Client
Telegram Office
TelegramOfficeStub
TelegramOfficeSkeleton
request/response
Connector Acceptor
ConnectionHandler
ConnectionHandler
connect
create
ConcurrencyStrategy
ThreadPerConnection
create
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 44
SE 1
Summary (2)
The Result
A flexible communication middleware for distributed systems.
‘Known Uses’ @ Siemens
• Warehouse Management
• Hot Rolling Mill Process Automation
• Medical Imaging
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 45
SE 1
Warehouse Core Interface
The Warehouse Core Interface
6 factors impact the design of the warehouse core interface:
• Multiple clients. There are many clients that operate on the warehouse core.
• Client diversity. Different kinds of clients use the warehouse core differently.
• Independence. Client views on the ware- house core should not affect its design.
• Extensibility. Integrating new client views should neither affect the warehouse core design nor its code.
• Housekeeping. Logging and, where possible, undo/redo should be supported.
• Real-time. The system has soft real-time requirements.
Proxy
DBMS
Proxy Broker
Bridge
Proxy*
** 0..1
View Controller
Client
CommunicationInfrastructure
UserInterface
FunctionalCore
Model
Persistence
1
11
1
1 1
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 46
SE 1
Client Access
Problem
When designing the client access to the warehouse core services we must consider
two aspects:
• Every kind of client uses the warehouse core differently. The warehouse core, however, should be independent of client-specific views on its services.
• It must be possible to integrate new kinds of ‘use cases’ for the warehouse core using existing services, but without affecting its design and implementation.
Equipment
Commissioning
Warehouse Core
Interface
AdministrationBasic
Automation
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 47
SE 1
Client Access
Solution
Shield the warehouse core interface from the way it is used by clients with the Command
pattern:
• Clients (e.g., Basic AutomationProxy) create concrete command objects that represent the operation they want to execute on the warehouse core.
• An Abstract Command class declares an interface for executing an operation.
• Concrete Commands (e.g., StoreItem) implement a concrete operation on the warehouse core.
• The Receiver (WarehouseCore) knows how to perform operations.
AdministrationProxy
Basic Autom.Proxy
Warehouse Core
EquipmentProxy
AbstractCommand
FetchItem
StoreItem
ItemTransport
*
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 48
SE 1
Optimizing The Command Hierarchy
Problem
Using the Command pattern results in overly many Concrete Command classes.
How can we minimize their number?
• The expressiveness of the original Command class hierarchy should be preserved.
• Many concrete commands can be composed of more elementary commands, such as Item Transport.
Warehouse Core
AbstractCommand
FetchItem
StoreItem
ItemTransport
TransportPlanning
BookEquipment
ReleaseEquipment
ReleaseLocation
Search forLocation
BookLocation
...
...
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 49
SE 1
Optimizing The Command Hierarchy
Solution
Reduce the size of the Command hierarchy by applying the Composite pattern:
• A Component (AbstractCommand) declares an interface for objects in a command composition.
• Leafs (e.g., FetchItem) represent the ‘atomic’ commands in the composition.
• A Composite (MacroCommand) implements the behavior for composed commands.
AdministrationProxy
Basic Autom.Proxy
Warehouse Core
EquipmentProxy
AbstractCommand
FetchItem
StoreItem
*
MacroCommand
*
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 50
SE 1
Simple Undo
Problem
Sometimes clients like to cancel a request.
• Commands should support their own cancellation, if allowed.
• The warehouse core should not be blown up with additional infrastructure, just because few commands are undoable.
Warehouse Core
Interface
#!
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 51
SE 1
Simple Undo
Solution
Support undoing individual commands with the Memento Pattern:
• A Memento stores parts of the internal state of the warehouse core before an undoable command is executed.
• Originators (e.g., MacroCommand) create
a memento before they start an operation on the warehouse core.
• The originators also embody the Caretaker role of the pattern. They are responsible for the memento’s safekeeping.
AdministrationProxy
Basic Autom.Proxy
Warehouse Core
EquipmentProxy
AbstractCommand
FetchItem
StoreItem
MacroCommand
Memento*
0..1
*
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 52
SE 1
Command Housekeeping
Problem
Client requests must be logged and scheduled, and we want to support multiple
undo/redo.
However, integrating housekeeping functionality with the existing commands is either tedious, such as for logging, or next
to impossible, as with scheduling and multiple undo/redo.
Warehouse Core
AbstractCommand
FetchItem
StoreItem
MacroCommand
Memento*
0..1
Logging 1. FetchItem2. BookEquipment3. SearchforLocation4. ...5. ...
SchedulingMultiple
Undo/Redo
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 53
SE 1
Command Housekeeping
Solution
Support command housekeeping by using the Command Processor Pattern:
• A Controller (TelegramOffice) creates command objects upon client requests and passes them to the Command Processor for execution.
• A Command Processor executes operat- ions on the warehouse core. Internally, it logs and schedules commands, and organizes their multiple undo/redo.
• Commands (e.g., StoreItem) implement the operations on the warehouse core.
• The Supplier (Warehouse Core) knows how to perform operations.
AdministrationProxy
Basic Autom.Proxy
Warehouse Core
EquipmentProxy
AbstractCommand
CommandProcessor
FetchItem
StoreItem
MacroCommand
Memento*
*
0..1
TelegramOffice
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 54
SE 1
Central Command Handling
Problem
To organize housekeeping functionality correctly, specifically scheduling, only one
Command Processor is allowed for the warehouse core.
• Clients need a defined access point to the one instance of the Command Processor.
• When requesting access to the Command Processor clients should be unaware of whether or not it already exists.
Warehouse Core
AbstractCommand
FetchItem
StoreItem
MacroCommand
Memento*
0..1
Logging
1. FetchItem2. BookEquipment3. SearchforLocation4. ...5. ...
SchedulingMultiple
Undo/Redo
Logging
1. FetchItem2. BookEquipment3. SearchforLocation4. ...5. ...
SchedulingMultiple
Undo/Redo
CommandProcessor 1
CommandProcessor 2
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 55
SE 1
Central Command Handling
Solution
Ensure that the Command Processor class has only one instance with the
Singleton Pattern:
• A Singleton (CommandProcessor) is responsible for creating its own unique instance and for providing an operation that lets clients access this instance.
AdministrationProxy
Basic Autom.Proxy
Warehouse Core
EquipmentProxy
AbstractCommand
CommandProcessor
FetchItem
StoreItem
MacroCommand
Memento*
*
0..1
TelegramOffice
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 56
SE 1
Logging and Scheduling
Problem
Different customers require different logging and scheduling mechanisms.
• Integrating different logging and scheduling mechanisms should not affect
general command handling.
• We may need to integrate new mechanisms at a later point in time, but do not want to touch existing code.
• Logging mechanisms may change at run-time, for example from logging everything to only logging specific kinds of commands.
1. FetchItem2. BookEquipment3. SearchforLocation4. ...5. ...
Warehouse Core
MaximumUrgency
First
EarliestDeadline
First
MinimumLatency
First
I want MUF!
But I want EDF!!
Scheduling
Execution
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 57
SE 1
Logging and Scheduling
Solution
Integrate logging and scheduling mechanisms with the Strategy Pattern:
• Two Strategies (LoggingStrategy, SchedulingStrategy) declare an interface common to all supported logging and scheduling strategies, respectively.
• Concrete Strategies (LogEverything, MUF) implement the logging and scheduling interface.
• The Context (CommandProcessor) is configured with a concrete logging strategy and a concrete scheduling strategy.
AdministrationProxy
Basic Autom.Proxy
Warehouse Core
EquipmentProxy
AbstractCommand
CommandProcessor
FetchItem
TelegramOffice
StoreItem
MacroCommand
Memento*
LoggingStrategy
LogEverything
1SchedulingStrategy
MUF
1
*
0..1
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 58
SE 1
Telegram to Command Conversion
Problem
Clients deliver telegrams to the warehouse core, but it only ‘understands’ commands.
The general mechanism for accepting a telegram and converting it into a command
object should thus be separated from converting a specific telegram.
A Client
Telegram Office
Command Objects
Command
Telegram
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 59
SE 1
Telegram to Command Conversion
Solution
Separate general telegram handling from their conversion into command objects with
the Abstract Factory Pattern:
• A Concrete Factory (CommandFactory) declares and implements an interface for creating commands from telegrams.
• An Abstract Product (AbstractCommand) declares an interface for a type of product object.
• Concrete Products (e.g., StoreItem) define product objects to be created.
An abstract factory is not needed, since there are no multiple ways to convert a specific telegram into a command.
AdministrationProxy
Basic Autom.Proxy
Warehouse Core
EquipmentProxy
AbstractCommand
CommandProcessor
FetchItem
TelegramOffice
StoreItem
MacroCommand
Memento*
LoggingStrategy
LogEverything
1SchedulingStrategy
MUF
1
*
0..1
CommandFactory
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 60
SE 1
Summary (1)
7 Patterns Define the Warehouse Core Interface
• Command shields the warehouse core from client-specific views on it.
• Composite helps minimizing the Command hierarchy.
• Memento supports command undo/redo.
• Command Processor supports logging, scheduling, and multiple undo/redo.
• Singleton helps creating only one Command Processor instance.
• Strategy supports configuring the Command Processor with specific scheduling and logging mechanisms.
• Abstract Factory separates telegram hand- ling from their conversion to commands.
AdministrationProxy
Basic Autom.Proxy
Warehouse Core
EquipmentProxy
AbstractCommand
CommandProcessor
FetchItem
TelegramOffice
StoreItem
MacroCommand
Memento*
LoggingStrategy
LogEverything
1SchedulingStrategy
MUF
1
*
0..1
CommandFactory
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 61
SE 1
Summary (2)
The Result
A flexible framework for amessage- or telegram-oriented interface
to a service component.
‘Known Uses’ @ Siemens
• Warehouse Management
• Passenger Information
• Hot Rolling Mill Process Automation
• Medical Imaging
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 62
SE 1
Warehouse Core
The Warehouse Core
4 factors key factors impact the design of the warehouse core:
• Physical Storage Representation. The physics of a real-world storage must be represented exactly.
• Storage Efficiency. Memory is a critical resource. It must be possible to represent even the largest warehouses though.
• Extensibility. Integrating new functionality and extending the representation of the warehouse structure should not affect the existing code, if possible.
• Task-orientation. Different ‘user services’ should be executable as independent tasks.
Proxy
DBMS
Proxy Broker
Bridge
Proxy*
** 0..1
View Controller
Client
CommunicationInfrastructure
UserInterface
FunctionalCore
Model
Persistence
1
11
1
1 1
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 63
SE 1
Physical Storage
Problem
There are many different real-world warehouses.
• Storage is organized hierarchically.
• The class structure of the system must allow to represent arbitrary storage structures.
• Customers sometime re-organize their warehouse structure. The system must follow such re-organizations at run-time.
• The structure must be extensible with new kinds of storage types.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 64
SE 1
Physical Storage
Solution
Represent physical storage with the Composite Pattern:
• A Component (AbstractStorage) declares an interface for objects in a storage representation.
• Leafs (e.g., Bin, Door) represent ‘atomic’ storage types. Transport Equipment is considered as mobile storage.
• A Composite (CompositeStorage) implements the behavior for composed storage, such as aisles, sides, and racks.
DoorBinComposite
Storage
*
Equipment
*
AbstractStorage
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 65
SE 1
Physical Storage
Problem
Clients are unaware to which storage component they deliver a request.
• The storage which receives the request might not be the intended receiver.
• The storage which receives the request does not know the intended receiver.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 66
SE 1
Physical Storage
Solution
Forward requests upwards the storage hierarchy via the Chain of Responsibility
Pattern:
• A Handler (AbstractStorage) defines an interface for handling requests.
• Concrete Handlers (e.g., Bin, Door, CompositeStorage) handle requests they are responsible for, otherwise they forward a request to their successor.
DoorBinComposite
Storage
*
Equipment
*
AbstractStorage
Successor
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 67
SE 1
Storage Organization
Problem
Storage is organized according to different organization criteria.
• Organization criteria are assigned to every
single storage.
• There should not be too much memory consumption for criteria representation.
• Significant parts of a warehouse share common organization criteria, such as all bins in an aisle.
HazardousClass
TemperatureClass
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 68
SE 1
Storage Organization
Solution
Represent storage organization criteria with the Flyweight Pattern:
• A Concrete Flyweight (SOC) declares and implements an interface for accessing a vector of storage organization criteria.
• A Client (AbstractStorage) maintains a reference to a flyweight.
• Not shown here: A Flyweight Factory (Initialization) creates and assigns new flyweights to a storage.
An abstract Flyweight is not needed, since only one flyweight type is needed in the system.
DoorBinComposite
StorageEquipment
*
SOC
*1
AbstractStorage
Successor
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 69
SE 1
Storage-specific Behavior
Problem
Storage may have individual behavior.
• Each individual storage should be configurable with appropriate behavior.
• Storage-specific behavior may change at run-time.
• Integrating new kinds of storage-behavior with the system should be possible, with as little modification of existing code as possible.
Storage Load-Behavior Options
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 70
SE 1
Storage-specific Behavior
Solution
Represent storage-specific behavior with the Strategy Pattern:
• An Abstract Strategy declares an interface for objects that represent storage-specific behavior.
• Concrete Strategies (e.g., LoadInLayers) implement the Abstract Factory interface in a specific manner.
• A Context (AbstractStorage) is configured with a Concrete Strategy which represents its specific behavior.
DoorBinComposite
Storage
*
Equipment
*
AbstractStrategy
LoadInLayers
SOC
1
AbstractStorage
Successor
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 71
SE 1
Warehouse Behavior
Problem
Some services operate on the whole warehouse structure.
• The implementation of such services should not depend on a a concrete warehouse representation.
• A concrete warehouse structure should not
be polluted with service-specific code.
• New such services may emerge over time and must be integrated.
Occupation?
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 72
SE 1
Warehouse Behavior
SolutionIntegrate warehouse behavior with the
Visitor Pattern, thereby preparing the system for future extensions:
• A Visitor (AbstractVisitor) declares a visit operation for each class in the Element structure.• ConcreteVisitors (e.g., Occupation) implement the visit operation for the specific Concrete Element it visits.• An Element (AbstractStorage) declares an accept operation that takes a visitor as an argument.• Concrete Elements (e.g., Door) implement the accept operation in an element- specific manner.
DoorBinComposite
Storage
*
Equipment
AbstractVisitor
*
AbstractStrategy
LoadInLayers Occupation
SOC
1
AbstractStorage
Successor
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 73
SE 1
Traversal
Problem
Some operations must traverse the warehouse storage structure.
• Different operations require different traversal strategies.
• The operation should not be dependent on the structure to be traversed.
• The traversal strategies an operation uses may change.
1 2 3 4
5
Occupation?
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 74
SE 1
Traversal
Solution
Encapsulate traversal strategies as objects with the Iterator Pattern:
• An Iterator (AbstractIterator) declares an interface for accessing and traversing an object structure.
• Concrete Iterators (e.g., LeafsOnly) implement a specific traversal algorithm on the object structure.
• An Aggregate (AbstractStorage) defines an interface for creating concrete Iterator objects that are able to traverse its inner structure.
DoorBinComposite
Storage
*
Equipment
AbstractIterator
AbstractVisitor
*
AbstractStrategy
LoadInLayers LeafsOnly Occupation
SOC
1
1
1
AbstractStorage
Successor
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 75
SE 1
Direct Access
Problem
Some operations need direct access to all ‘entities’ of a certain kind.
• The operation should not be dependent on the entities to which it requires access.
• The operation should not need to provide special data structures for maintaining the entirety of all entities.
• Individual entities should not need to provide infrastructure for maintaining their entirety.
Who is drivingforklift 42?
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 76
SE 1
Direct Access
Solution
Introduce components for managing entities of a specific kind with the Manager Pattern:
• A manager (StorageManager) implements services for maintaining entities of a certain kind.
• Subjects (AbstractStorage) represent the entities being managed.
• Clients (not shown here) use the manager to get direct access to a specific
entitiy.DoorBin
CompositeStorage
*
Equipment
AbstractIterator
AbstractVisitor
*
AbstractStrategy
LoadInLayers LeafsOnly Occupation
SOC
1
1
StorageManager
*
1
AbstractStorage
Successor
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 77
SE 1
Load on Demand
Problem
A complete representation of the warehouse structure is too memory expensive. It is thus
stored in a DBMS.
However, we need every concrete part of the structure in memory as soon as a client
requires access to it.
DBMS
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 78
SE 1
Load on Demand
Solution
Defer loading an object into memory with the Proxy Pattern:
• A client (e.g., a Visitor) needs access to a certain storage data which is not available in memory.
• A proxy (e.g., AbstractStorage) represents the data and organizes its loading on demand as well as its release after usage.
• An original (StorageOriginal) contains the data that the proxy loads.DoorBin
CompositeStorage
*
Equipment
AbstractIterator
AbstractVisitor
*
AbstractStrategy
LoadInLayers LeafsOnly Occupation
SOC
1
1
*
1
AbstractStorage
DBMSStorage
Original
StorageManager
Successor
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 79
SE 1
Integration (1)
Using the Warehouse Structure
The design of the warehouse structure representation and management is
implemented as a separate component within the system’s functional core.
It is used by so-called task-components which represent the ‘user services’ the
system offers, such as Item Transport, Item Storing, Item Fetching, and Replenishment.
The task-components also shield the warehouse structure from unauthorized
access, and its clients from design specifics.
DoorBinComposite
Storage
*
Equipment
AbstractIterator
AbstractVisitor
*
AbstractStrategy
LoadInLayers LeafsOnly Occupation
SOC
1
1
StorageManager
*
ItemTransport
1
AbstractStorage
DBMSStorage
Original
Successor
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 80
SE 1
Integration (2)
Communication with the System
The Warehouse Structure component communicates with the real-world
warehouse via telegrams.
Objects representing proactive physical entities of the warehouse, such as forklifts,
transport belts, and rack servers, communicate with the telegram office to
control the real-world.
The telegram office receives messages from the warehouse structure, converts them,
with help of a telegram factory into telegrams and sends them to their receiver.
DoorBinComposite
Storage
*
Equipment
AbstractIterator
AbstractVisitor
*
AbstractStrategy
LoadInLayers LeafsOnly Occupation
SOC
1
1
StorageManager
*
TelegramOffice
1
AbstractStorage
DBMSStorage
Original
TelegramFactory
Successor
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 81
SE 1
Summary (1)
8 Patterns Define the Representation of the Warehouse Structure
• Composite and Chain of Responsibility specify the storage hierarchy.
• Flyweight supports implementing storage organization criteria efficiently.
• Strategy supports the integration of storage-specific behavior.
• Visitor helps implementing storage- general services.
• Iterator supports traversing the warehouse structure.
• Manager allows direct access to elements of the warehouse structure.
• Proxy supports loading data on demand.
DoorBinComposite
Storage
*
Equipment
AbstractIterator
AbstractVisitor
*
AbstractStrategy
LoadInLayers LeafsOnly Occupation
SOC
1
1
*
1
AbstractStorage
DBMSStorage
Original
StorageManager
Successor
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 82
SE 1
Summary (2)
The Result
An adaptable and extensible design for representing arbitrary warehouse structures.
‘Known Uses’ @ Siemens
• SICALIS Warehouse Management
DoorBinComposite
Storage
*
Equipment
AbstractIterator
AbstractVisitor
*
AbstractStrategy
LoadInLayers LeafsOnly Occupation
SOC
1
1
*
1
AbstractStorage
DBMSStorage
Original
StorageManager
Successor
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 83
SE 1
Let’s reflecton the ‘stuff’
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 84
SE 1
Projects
Project Experience
• Warehouse Management
• Hot Rolling Mill Process Automation
• Medical Imaging
• Network Management
• Passenger Information
• Object Request Brokers
TAO, The Ace ORB
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 85
SE 1
Observation (1)
Frameworks were often NOT our original goal
For most projects the primary goals were extensibility and adaptability.
Through careful ‘design for evolution and change’ we received software architectures
that are stable in their core, yet being extensible with new structures,
modifiable with respect to existing structures, and adaptable to customer-
specific requirements.
In other words, the frameworks were ‘just’ a by-product.
DoorBinComposite
Storage
*
Equipment
AbstractIterator
AbstractVisitor
*
AbstractStrategy
LoadInLayers LeafsOnly Occupation
SOC
1
1
StorageManager
*
TelegramOffice
1
AbstractStorage
DBMSStorage
Original
TelegramFactory
Successor
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 86
SE 1
Observation (2)
One Size Does Not Fit All
Patterns alone are NOT sufficient enough for building systems that meet today’s
tough requirements.
• DOC provides the communication infrastructure.
• Frameworks support building architectures
for system families.
• Patterns help designing the frameworks.
• Components help configuring the frameworks to a customer-specific application.
DoorBinComposite
Storage
*
Equipment
AbstractIterator
AbstractVisitor
*
AbstractStrategy
LoadInLayers LeafsOnly Occupation
SOC
1
1
StorageManager
*
TelegramOffice
1
AbstractStorage
DBMSStorage
Original
TelegramFactory
Successor
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 87
SE 1
Benefits
Benefits
• Solutions to design problems are based on well-proven standard concepts.
• Consideration of alternatives are possible.
• Explicit consideration of non-functional aspects.
• Improved Communication.
• Improved Documentation.
• Knowledge is available to the whole organization.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 88
SE 1
Problems
Problems
• Hype.
• Finding the right patterns is not always easy.
• Implementing a pattern correctly needs some experience.
• Using patterns does not necessarily results
in a high-quality design.
• People often see patterns as blueprints.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 89
SE 1
Lessons Learned
Lessons Learned
• Patterns help, but are no silver bullet.
• Patterns complement but do not replace existing technology and methods.
• Education is crucial for success.
• Don’t force developers in using the patterns.
• Apply patterns carefully.
• JUST DO IT!
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 90
SE 1
The Patterns
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 91
SE 1
Broker (1)
Broker
Problem
Large-scale distributed systems require
• an inter-process communication infrastructure;
• location transparency of components;
• independence of application components from platform specifics; and
• independence of application components from implementation details of components they use.
MunichCity Info
Server
City InfoTerminal
LondonCity Info
Server
UNIX
Windows NT
UNIX
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 92
SE 1
Broker (2)
Solution
Introduce a broker component to achieve better decoupling of clients and servers.
• Servers provide functionality other application components can use.
• Clients are application components that use the services offered by servers.
• A broker is a messenger for transmitting requests between clients and servers.
• Client-side and server-side proxies represent components in a remote address space and shield clients from broker specifics.
• Bridges enable communication between different brokers.
Client
* *
**** 0..1
Client-SideProxy
pack_dataunpack_datasend_requestreturn
call_serverstart_taskuse_Broker
Server-SideProxy
pack_dataunpack_datacall_servicesend_response
Server
initializemain_looprun_serviceuse_Broker
Bridge
pack_dataunpack_dataforward_msgreceive_msg
Broker
event_loopregister_servicefind_serverfind_clientforw_requestforw_response
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 93
SE 1
Broker (3)
Benefits
• Location transparency.
• Changeability and extensibility of components.
• Portability.
• Interoperability between different Broker systems.
• Reusability.
• ‘Easy’ component testing.
Liabilities
• Restricted efficiency.
• Lower fault tolerance.
• Hard integration testing.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 94
SE 1
Model-View-Controller (1)
Model-View-Controller
Problem
User interfaces are prone to change requests. When developing an interactive
software system, you thus have to consider two aspects:
• Changes to the user interface should be easy, and possible at run-time; and
• Adapting or porting the user interface should not impact code in the functional
core of the application.
The System
SystemOutputUser
Input
UserInput
versus
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 95
SE 1
Model-View-Controller (2)
Solution
Divide an interactive application into three areas: processing, output and input:
• The model encapsulates core data and functionality. It is independent of specific
output representations or input behavior.
• Views display information to the user, by. obtaining data from the model. There can
be multiple views of the model.
• Controllers receive input, usually as events. Events are translated to service requests, which are sent either to the model or to their view.
*Observer
update
Model
attachObsdetachObsnotifygetDataservice
observerscoreData
Controller
inithandleEventupdate
myModelmyView
View
initmakeControlleractivatedisplayupdate
myModelmyController
1 1
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 96
SE 1
Model-View-Controller (3)
Benefits
• Multiple views of the same model.
• Synchronized views.
• Pluggable’ views and controllers.
• Exchangeability of ‘look and feel.’
• Reusable functionality.
• Framework potential.
Liabilities
• Increased complexity.
• Potential for excessive number of updates.
• Close coupling of views and controllers to a model.
• Inefficiency of data access in view.
• Inevitability of change to view and controller when porting.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 97
SE 1
Layers (1)
Layers
Problem
A characteristic of many systems is a mix of low- and high-level issues, where high-level operations rely on the lower-level ones. The
system’s design should consider that:
• Similar responsibilities should be grouped;
• Complex aspects need decomposition; and
• Components of the system should be exchangeable.
The System
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 98
SE 1
Layers (2)
Solution
Structure your system into an appropriate number of layers and place them on top of
each other.
• Start at the lowest level of abstraction. Call it layer 1. This is the base of your system.
• Work your way up the abstraction ladder by putting layer J on top of layer J-1.
• until you reach the top level of functionality—call it layer N.Layer 1
Layer 2
Layer 3
Layer 5
Layer 4
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 99
SE 1
Layers (3)
Benefits
• Reuse of layers.
• Support for standardization.
• Dependencies are kept local.
• Exchangeability.
Liabilities
• Cascades of changing behavior.
• Lower efficiency.
• Unnecessary work.
• Difficulty of establishing the correct granularity of layers.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 100
SE 1
Adapter (1)
Adapter
Problem
Sometimes interfaces of components that must cooperate do not match. The solution to this problem must take into account that:
• The components should be independent of
each other; and
• Component interfaces may not be modifiable, for example components from 3rd party vendors.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 101
SE 1
Adapter (2)
Solution
Convert the interface of a component into an another interface clients expect:
• Clients collaborate with components conforming to the target interface.
• Target defines the specific interface that clients use or expect.
• An adaptee defines a component whose interface needs adapting.
• An adapter adapts the interface of the adaptee to the target interface.
Target
request
Client
1
Adaptee
specificRequest
Adapter
request
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 102
SE 1
Adapter (3)
Benefits
• Cooperating components stay independent of each other.
Liabilities
• Lower efficiency.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 103
SE 1
Wrapper Facade (1)
Wrapper Facade
ProblemMany low-level APIs differ in syntax, even
if they share semantics. Yet
• applications should be portable to different platforms;
• direct dependencies of application code to these APIs should be avoided; and
• applications should use these APIs correctly and consistently.
The Systemfu
ncti
on1(
)
func
tion
2()
OS XX
f1()
f2()
OS YY
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 104
SE 1
Wrapper Facade (2)
Solution
Encapsulate functions and low-level data structures within classes :
• Functions are existing low-level functions and data structures.
• Wrapper Facades shield clients from dependencies to the functions by providing methods that forward client invocations to the functions.
• A client accesses the low-level functions via wrapper facades.
Functions
function
WrapperFacade
method
Client
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 105
SE 1
Wrapper Facade (3)
Benefits
• Robustness.
• Portability.
• Modularity.
Liabilities
• Additional indirection.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 106
SE 1
Forwarder-Receiver (1)
Forwarder-Receiver
ProblemMany components in a distributed system
communicate in a peer to peer fashion.
• The communication between the peers should not depend on a particular IPC mechanism;
• Performance is (always) an issue; and
• Different platforms provide different IPC mechanisms.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 107
SE 1
Forwarder-Receiver (2)
SolutionEncapsulate the inter-process communication mechanism:
• Peers implement application services.
• Forwarders are responsible for sending requests or messages to remote peers using a specific IPC mechanism.
•Receivers are responsible for receiving IPC requests or messages sent by remote peers using a specific IPC mechanism and dispatching the appropriate method of their intended receiver.
Forwarder
marshaldeliversendMessage
Peer 1
service
Peer 2
service
Forwarder
marshaldeliversendMessage
Receiver
receiveunmarshalreceiverMessage
Receiver
receiveunmarshalreceiverMessage
Here
There
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 108
SE 1
Forwarder-Receiver (3)
Benefits
• Efficient IPC.
• Encapsulation of IPC mechanisms.
Liabilities
• Hard to re-configure.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 109
SE 1
Reactor (1)
Reactor
ProblemIn distributed systems servers must handle
client requests effectively:
• They must be able to handle requests even if they are waiting for other requests to arrive;
• Latency should be minimized, throughput should be maximized;
• Integrating of new services should not break existing event handling code; and
• The use of concurrency strategies should be simplified.
Object 1
Object 2
Object 3
m1(
)
m2(
)
m3(
)
m4(
)
m5(
)
m6(
)
An Event
Which Object?Which Method?
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 110
SE 1
Reactor (2)
Solution-StructureDecouple application-specific event
dispatching from general event dispatching and synchronous event demultiplexing:
• Handles identify communication endpoints.
• A synchronous event demultiplexer blocks awaiting events to occur on a set of handles.
• An initiation dispatcher dispatches events onto event handlers which can dynamically register and unregister with the initiation dispatcher.
• Event handlers implement the application services and dispatching of events onto their concrete methods.
Event Handler
handle_eventget_handle
Concrete Event Handler 1
handle_eventget_handleservice
InitiationDispatcher
handle_eventsregister_handlerremove_handler
Sync. EventDemultiplexer
select
Handle
*
owns
notifies
<<uses>>
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 111
SE 1
Reactor (3)
Solution-Dynamics• The application registers event handlers with the initiation dispatcher.
• The initiation dispatcher requests each event handler to pass back its handle.
• The event handling is started; the initiation dispatcher calls the synchronous event demultiplexer to wait for events to occur on the handles.
• The synchronous event demultiplexer notifies the initiation dispatcher when a handle becomes ‘ready.’
• The initiation dispatcher triggers the event handler represented by the handle to process the event.
• The event handler processes the event.
ApplicationEvent
Handler
register_handler
get_handle
handle_eventsselect
handle_event
EventDemuxer
service
InitiationDispatcher
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 112
SE 1
Reactor (4)
Benefits
• Separation of concerns.
• Configurability and extensibility with new services.
• Course-grained concurrency control.
• Portability.
Liabilities
• Restricted applicability, since it requires the underlying operating system to support handles.
• Event handlers are not preemted while they are executing.
• Hard to debug.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 113
SE 1
Acceptor-Connector (1)
Acceptor-Connector
ProblemIn distributed systems peers that like to
communicate must first establish a connection:
• Connection establishment is largely independent of communication between peers;
• Communication roles of peers may change; and
• Strategies for communication establishment change much less frequently than application-service implementations.
Connect Me
Request / Response1
2
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 114
SE 1
Acceptor-Connector (2)
Solution-StructureDecouple connection establishment from
subsequent service processing:
• Service handlers provide methods every remotely accessible service must support.
• A Connector actively establishes connections to remote service handlers.
• An acceptor passively waits for connection requests send by remote service handlers.
• Concrete service handlers, connectors, and acceptors implement the generic components in an application-specific manner.
• An initiation dispatcher routes requests.
Connector
connectcompletehandle_event
ConcreteAcceptor
InitiationDispatcher
handle_eventsselect
* Acceptor
acceptopenhandle_event
ServiceHandler
openhandle_event
**
ConcreteConnector
ConcreteServiceHandlers
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 115
SE 1
Acceptor-Connector (3)
Solution-Dynamics• A server application registers the acceptor with the initiation dispatcher.
• The event handling is started; the initiation dispatcher notifies the acceptor when it receives a connection request.
• The acceptor initializes the service handler and passes the transport endpoint to it on which the connection request arrived.
• The service handler registers itself with the initiation dispatcher.
• The initiation dispatcher triggers the service handler whenever a request arrives it registered for at the transport endpoint.
• The service handler processes the event.
Application Acceptor
register_handler
handle_events
accept
InitiationDispatcher
service
ServiceHandler
open
open registerhandler
handle_event
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 116
SE 1
Acceptor-Connector (4)
Solution-Dynamics• A server application calls the connector to establish a connection to a remote peer.
• When the connection is established, the connector calls the service handler to register with the initiation dispatcher
and passes the previously created transport endpoint to it.
• The initiation dispatcher triggers the service handler whenever a request arrives it registered for at the transport endpoint.
• The service handler processes the event.
Application Conector
handle_events
InitiationDispatcher
service
ServiceHandler
connectopen register_
handler
handle_event
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 117
SE 1
Acceptor-Connector (5)
Benefits
• Reusability of connection establishment software.
• Robustness by shielding transport endpoints from direct access and misuse.
• Utilization of concurrency.
• Extensibility with new connection establishment algorithms.
Liabilities
• Additional indirection.
• Additional overhead for applications that follow a pure client/server model.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 118
SE 1
Active Object (1)
Active Object
ProblemIf multiple clients share an object which
resides in a separate thread of control, we must coordinate access to it:
• Methods invoked on the object should not block the entire process thus downgrading the QoS of other objects.
• Synchronized access to the object should be simple.
• Clients should be unaware of the parallelism.
Object
Servant Thread
Client 1
Client 2Client 3
Client Thread
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 119
SE 1
Active Object (2)
Solution-StructureDecouple method invocation from method
execution:
• A proxy provides an interface that allows clients to access methods of an object.
• A concrete method request is created for every method invoked on the proxy.
• A scheduler receives the method requests and dispatches them on the servant when they become runnable.
• An activation queue maintains pending method requests.
• A servant implements the methods.
• A future allows clients to access the results of a method call on the proxy.
Future
Scheduler
enqueue dispatch
MethodRequest
guardcall
*
ConcreteMethodRequest1
Proxy
method_1method_N
ActivationQueue
enqueuedequeue
Servant
method_1method_N
ConcreteMethodRequest2
creates creates maintains
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 120
SE 1
Active Object (3)
Solution-Dynamics• A client invokes a method on the proxy.
• The proxy returns a future to the client, and creates a method request which it passes to the scheduler.
• The scheduler enqueues the method request into the activation queue (not shown here).
• When the method request becomes runnable, the scheduler dequeues it from the activation queue (not shown here) and executes it.
• The method request executes the method on the servant and writes results, if any, to the future.
• Clients obtain the method’s results via the future.
method
enqueue
Client Proxy
Future
Scheduler
MethodRequest
Servant
dispatch call method
read
write
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 121
SE 1
Active Object (4)
Benefits
• Enhances concurrency.
• Simplifies synchronized access to a shared object that resides in its own thread of control.
• Transparent leveraging of available parallelism.
Liabilities
• Method execution order can differ from method invocation order.
• Performance overhead.
• Complicated debugging.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 122
SE 1
Strategy (1)
Strategy
ProblemSometimes a system must support more
than one algorithm for computing a certain result. However:
• Clients do not want to be dependent on which algorithm is used.
• Which algorithm is the most effective may
change at run-time.
• We want to integrate new algorithms over time, but without modifying existing code, if possible.
SortData
HeapSort
QuickSort
MergeSort
BottomUpHeapSort
One Service Many Algorithms
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 123
SE 1
Strategy (2)
Solution
Encapsulate each algorithm as a separate object:
• Strategy declares an interface common to all supported algorithms.
• Concrete Strategies implement the strategy interface for a specific algorithm.
• Context offers a service to clients and is configured with a concrete strategy.
Strategy
algorithm
ConcreteStrategy
algorithm
Context
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 124
SE 1
Strategy (3)
Benefits
• Support for families of algorithms.
• Elimination of specific conditional statements.
• Choice of different algorithms.
• Extensibility with new algorithms.
Liabilities
• Clients must be aware of strategies.
• Communication overhead between context and strategies.
• Increased number of classes.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 125
SE 1
Abstract Factory (1)
Abstract Factory
ProblemCreating some kinds of objects is a complex
activity. However
• clients which request the creation of such an object should not be dependent on its construction process; and
• we often want to support the creation of families of related objects, for example when creating windows on different platforms.
A Client
Logging
1. FetchItem2. BookEquipment3. SearchforLocation4. ...5. ...Scheduling
MultipleUndo/Redo
CommandProcessor 1
Singleton
Problem
There are components of which there should or must be only one instance in a system. When solving this problem we
must consider that:
Gotcha!
Create New Window
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 126
SE 1
Abstract Factory (2)
Solution
Separate the creation of objects from their use:
• An Abstract Factory declares an interface for operations that create abstract products.
• Concrete Factory implement the abstract factory interface for creating specific products.
• Abstract Products declare interfaces for a type of product.
• Concrete Products defines a product to be created by the corresponding concrete factory.
AbstractFactory
createProductAcreateProductB
ConcreteFactory
createProductAcreateProductB
AbstractProductA
ProductA
ConcreteProductA
ProductA
AbstractProductB
ProductB
ConcreteProductB
ProductB
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 127
SE 1
Abstract Factory (3)
Benefits
• Separation of concerns.
• Exchangeability of products.
• Promotes consistency among products.
Liabilities
• Integration of new products is not always easy.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 128
SE 1
Service Configurator (1)
Service Configurator
ProblemIt may be necessary to re-configure a system with a different set of service components than done in its original
configuration. However,
• The re-configuration must happen at run- time; and
• Services must be initialized, suspended, resumed, and terminated dynamically.
Application
Component 3Component 1
Component 2
Component CComponent A
Component B
Current Configuration
New Configuration
Changeto
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 129
SE 1
Service Configurator (2)
Solution-Structure
Centralize the system’s configuration with services in a separate component.
•A service defines a common interface for all configurable services.
• Concrete services implement specific configurable services.
• A service repository maintains the currently configured and loaded services.
• A service configurator can dynamically load services to, and unload from, the service repository, and execute them.
ServiceConfigurator
install uninstall
*
ServiceRepository
insertremove
Service
initfinisuspendresumeinfoservice
ConcreteService1
ConcreteService2
maintains
installs
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 130
SE 1
Service Configurator (3)
Solution-Dynamics
• The service configurator loads all services
of a particular configuration, initializes them and inserts them into the service repository.
• The services serve client requests.
• When uninstalling the current configuration, for example, to prepare a new configuration, the service configurator terminates all services and removes them from the service repository.
ServiceConfigurator
Service AService
RepositoryService B
service
service
initinsert
insert
install
finiremove
remove
uninstall
fini
init
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 131
SE 1
Service Configurator (4)
Benefits
• Centralized administration.
• Increased configuration dynamism.
Liabilities
• Lack of determinism, since configuration is done at run-time.
• Increased overhead compared to statically configured systems.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 132
SE 1
Command (1)
Command
ProblemWhen issuing a request to a system
• clients sometimes do not know anything about the operation being requested or the receiver of the request;
• the system is not necessarily interested in knowing how clients use its services;
• different clients may use the same system services differently; and
• new kinds of client requests may emerge over time, but we do not want to touch existing code when integrating them.
The System
Request!
Conversion
Ope
rati
on
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 133
SE 1
Command (2)
Solution
Encapsulate requests as objects:
• Command declares an interface for executing an operation.
• Concrete Commands implement the command interface for a specific operation.
• The client creates a command object and sets its receiver.
• The invoker asks the command to carry out its request.
• The receiver knows how to perform operations.
Command
execute
Receiver
action
ConcreteCommand
execute
Invoker
Client
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 134
SE 1
Command (3)
Benefits
• Decouples the object that invokes the operation from the object that knows how to perform it.
• Commands are first-class objects.
• Extensibility with new commands.
Liabilities
• Many command classes.
• Clients must know the concrete commands.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 135
SE 1
Composite (1)
Composite
ProblemWhen representing whole-part hierarchies
• clients do not want to distinguish whether they currently cooperate with a compound object or an atomic object; and
• the hierarchical structure of the compound
object should be preserved.
Client
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 136
SE 1
Composite (2)
Solution
Represent compound objects as tree structures:
• Component declares an interface for objects in the composition.
• Leafs represent ‘atomic’ objects in the composition.
• Composite defines behavior for composed objects.
• The client manipulates objects in the composition.
Leaf
operation
Client Component
operationaddCompremoveCompgetChild
Composite
operationaddCompremoveCompgetChild
*
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 137
SE 1
Composite (3)
Benefits
• Clients are shielded from the object hierarchy.
• Extensibility with new leafs.
• Lets you build arbitrary object hierarchies.
Liabilities
• Can make your design overly general.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 138
SE 1
Memento (1)
Memento
ProblemSometimes we need access to an object’s
internal state. However,
• we do not want to break the object’s encapsulation;
• we do not want to expose implementation details of the object; and
• we only need access to selected aspects of the state information.
ObjectOperation
Client
State
ObjectOperation State’
Do
ObjectOperation State
Undo
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 139
SE 1
Memento (2)
Solution
Capture the internal state of the object in a separate snapshot object:
• A memento stores the internal state of the originator object.
• The originator creates a memento containing a snapshot of its current state.
• A caretaker is responsible for the memento’s safekeeping.
Caretaker
Originator
state
setMementocreateMemento
Memento
state
setStategetState
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 140
SE 1
Memento (3)
Benefits
• Preserving encapsulation boundaries.
• Simplifying the originator.
Liabilities
• Using mementos might be expensive.
• Hidden costs in caring for mementos.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 141
SE 1
Command Processor (1)
Command Processor
ProblemIn the context of request handling we
sometimes need to implement additional housekeeping services, such as logging, scheduling, command suspension, and
multiple undo/redo.
However, implementing such services as part of the request objects themselves
• may result in overly complex code, such as for logging and multiple undo/redo, or
• is next to impossible, such as for scheduling and command suspension.
Client SystemOperation
Do
DBMS
Log Request
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 142
SE 1
Command Processor (2)
Solution
Introduce a central request handling instance:
• Command declares an interface for executing an operation.
• Concrete Commands implement the command interface for a specific operation.
• Controllers create a command objects and pass them to the command processor.
• A command processor is responsible for executing commands and for additional command housekeeping.
• Suppliers know how to perform operations.
Command
execute
Supplier
action
ConcreteCommand
execute
Controller
CommandProcessor
commandStack
doCmdundoCmdscheduleCmdlogCmd
*
*
1
1
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 143
SE 1
Command Processor (3)
Benefits
• Flexibility in request activation.
• Central request handling.
• Testability at application level.
• Easy integration of execution-related housekeeping services.
• Potential for concurrent command execution.
Liabilities
• Efficiency.
• Command Processor with overly many responsibilities.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 144
SE 1
Singleton (1)
Singleton
ProblemThere are components of which there
should or must be only one instance in a system. When solving this problem we must
consider that:
• clients need a defined access point to this one instance; and
• when requesting access to the one instance clients should be unaware of whether or not it already exists.
Window Manager
Logging
1. FetchItem2. BookEquipment3. SearchforLocation4. ...5. ...Scheduling
MultipleUndo/Redo
CommandProcessor 1
Singleton
Problem
There are components of which there should or must be only one instance in a system. When solving this problem we
must consider that:
Gotcha!
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 145
SE 1
Singleton (2)
Solution C++
• Declare the constructor of the class as private.
• Declare a static member variable theInstance that refers to the single existing instance of the class.
• Initialize this pointer to zero in the class implementation file.
• Define a public static member function getInstance() that returns the value of theInstance.
• The first time getInstance() is called, it will create the single instance with new and assign its address to theInstance.
class Singleton { static Singleton *theInstance; Singleton();public: static Singleton *getInstance() { if (! theInstance) theInstance = new Singleton; return theInstance; }};
//...Singleton* Singleton::theInstance = 0;
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 146
SE 1
Singleton (3)
Solution Smalltalk
• Override the class method new to raise an error.
• Add a class variable TheInstance that holds the single instance.
• Implement a class method getInstance that returns TheInstance.
• The first time getInstance is called, it will create the single instance with super new and assign it to TheInstance.
new self error: 'cannot create new object'
getInstance TheInstance isNil ifTrue: [TheInstance := super new]. ^TheInstance
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 147
SE 1
Singleton (4)
Benefits
• Controlled instantiation process.
• Controlled access to sole instance.
• Permits a variable number of instances.
Liabilities
• How to delete a Singleton?
• How to make a Singleton thread-safe?
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 148
SE 1
Template Method (1)
Template Method
ProblemSometimes it is possible to provide an invariant skeleton for a specific service
which concrete implementations vary only in certain details.
• We want to implement the service skeleton in a way it can be configured with a specific implementation of the variant details; and
• We want to avoid accidental overriding of the service skeleton.
SortData
HeapSort
QuickSort
MergeSort
BottomUpHeapSort
A Core Service and possibleconfigurations
sort
sort
sort
sort
SortData() { X=readData(); sort(X) storeData();};
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 149
SE 1
Template Method (2)
Solution
Define the skeleton of an algorithm in an operation, deferring some steps to
subclasses:
• An Abstract Class implements the skeleton of an algorithm and defines interfaces for primitive operations which the skeleton implementation uses.
• Concrete Classes implement the primitive operations in an application- specific way.
AbstractClass
templateMethodhookMethod1hookMethod2
ConcreteClass
hookMethod1hookMethod2
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 150
SE 1
Template Method (3)
Benefits
• Fundamental reuse technique.
Liabilities
• Potential for overly many concrete classes.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 151
SE 1
Chain of Responsibility (1)
Chain of Responsibility
ProblemWhen clients issue a request either more than one object may be responsible for
handling it or the object which receives the request may not be responsible for its
handling.
• clients may not want to know whether object to which they send the request is responsible for its handling; and
• the object that receives the request may not know the intended receiver.
Client
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 152
SE 1
Chain of Responsibility (2)
Solution
Connect the objects that can handle a request via a chain:
• Handler declares an interface for handling a request.
• Concrete Handlers handle requests they are responsible for, otherwise they forward a request to their successor.
ConcreteHandler1
handleRequest
Client Handler
handleRequest
ConcreteHandler2
handleRequest
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 153
SE 1
Chain of Responsibility (3)
Benefits
• Reduced coupling.
• Flexibility in assigning requests to objects.
Liabilities
• Receipt and handling is not guaranteed.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 154
SE 1
Flyweight (1)
Flyweight
ProblemSometimes many objects depend on the
same other objects.
• Providing each of the many objects with its own copy of the shared object is too memory expensive.
• The shared objects may change at run- time.
A Word Another Word
Dilbert Dogbert
D i l b e r t o g
Words share Letters
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 155
SE 1
Flyweight (2)
Solution
Use sharing to give the many objects access to the objects on which they commonly
depend:
• Flyweight declares an interface through which flyweights can receive and act on extrinsic state.
• Concrete Flyweight implements the Flyweight interface and adds storage for intrinsic state.
• Unshared Concrete Flyweight enables sharing by having Concrete Flyweights as children.
• The client maintains a reference to flyweights.
Client
*
FlyweightFactory
GetFlyweight
Flyweight
operation
ConcreteFlyweight
intrinsicState
operation
UnsharedConcreteFlyweight
allState
operation
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 156
SE 1
Flyweight (3)
Benefits
• Storage savings.
Liabilities
• Run-time costs with transferring, finding, and computing extrinsic state.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 157
SE 1
Visitor (1)
Visitor
ProblemOperations on a complex object structure
are hard to implement.
• The implementation of the operation should not be dependent on specific configurations of the object structure on which it operates.
• The object structure shouldn’t be dependent on a specific implementation of the operation.
val = 1
val = 35 val = 2
val = 42
val = 4
Sum Values
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 158
SE 1
Visitor (2)
Solution
Represent the operation separately from the object structure on which it operates:
• Visitor declares a generic interface for every potential element-specific part of the operation.
• Concrete Visitor implements a specific operation and its element-specific parts.
• Element defines an operation that accepts a visitor as an argument.
• Concrete Elements implement the accept operation by calling the element-specific sub-operation of the accepted visitor.
Element
accept
ConcreteElementA
accept
Visitor
visitAvisitB
ConcreteElementB
accept
ConcreteVisitor
visitAvisitB
v->visitA(this)
v->visitB(this)
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 159
SE 1
Visitor (3)
Benefits
• Integrating new operations is easy.
• Central implementation of global functionality.
• Support for accumulating state.
Liabilities
• Breaking encapsulation.
• Hard to extend visitors.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 160
SE 1
Iterator (1)
Iterator
ProblemSometimes you want to access an aggregate
object’s contents.
• The client that needs access should not be dependent on the internal structure of the aggregate.
• The aggregate should not expose its internal structure.
• The client may need access to different parts of the aggregate at different points in time.
val = 1
val = 35 val = 2
val = 42
val = 4
Depth FirstTraversal
Sum Values
Uses
Traverses
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 161
SE 1
Iterator (2)
Solution
Encapsulate the access strategy to an aggregate into a separate object:
• Iterator declares a generic interface for accessing and traversing an aggregate.
• Concrete Iterator implement specific access and traversal strategies.
• Aggregate declares an interface for creating Concrete Iterators.
• Concrete Aggregate implements the interface to return a specific Concrete Iterator being ablle to access and traverse its inner structure.
Iterator
firstnextcurrent
ConcreteIterator
Aggregate
createIterator
ConcreteAggregate
createIterator
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 162
SE 1
Visitor (3)
Benefits
• Integrating new traversal and access strategies is easy.
• Iterators simplify aggregate interfaces.
• Support multiple traversals simultaneously.
Liabilities
• Robustness.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 163
SE 1
Manager (1)
Manager
ProblemSome clients require direct access to a
certain kind of objects. However
• clients are not aware of the exact location of the object which they like to access; and
• neither the client nor the objects should provide infrastructure for supporting the management of the objects’ entirety.
Bring toFront
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 164
SE 1
Manager (2)
Solution
Provide an object for maintaining the entirety of a certain class of objects:
• A Manager implements maintenance for certain class of objects and allows direct access to its instances.
• Suppliers are the ‘managed objects’.
• Clients use the manager to get access to specific suppliers.
Manager
getSupplierfindSupplierloadSupplier
Supplier
Client
*
1
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 165
SE 1
Manager (3)
Benefits
• Separation of concerns.
• Variation of management functionality.
Liabilities
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 166
SE 1
Proxy (1)
Proxy
ProblemSometimes it is impossible to access an
object directly.
However, accessing the object should be efficient and transparent.
Real Thing
Client
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 167
SE 1
Proxy (2)
Solution
Provide a placeholder for the object through which clients can access it
• An Original implements the object which is not directly accessible.
• A Proxy represents the Original and ensures the correct access to it. The Proxy usually offers the same interface as the Original.
• Clients use the Proxy to get access to the Original.
Proxy
service
Client
Original
service1 1
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 168
SE 1
Proxy (3)
Benefits
• Access control to originals.
• Memory savings.
• Performance gaining (cache proxy).
• Separation of housekeeping and functionality.
Liabilities
• Potential overkill, if proxies include overly sophisticated functionality.
• Level of indirection.
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 169
SE 1
The End
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 170
SE 1
References (1)
ReferencesC. Alexander: The Timeless Way of
Building, Oxford University Press, 1979
M. Fowler: UML Distilled, Addison-Wesley,
1997
R.P. Gabriel: Patterns of Software, Oxford University Press, 1996
E. Gamma, R. Helm, R. Johnson, J. Vlissides: Design Patterns – Elements of Reusable Object-Oriented Software, Addison-Wesley, 1995
Various Eds. : Pattern Languages of Program Design, Vol. 1- 3, Addison-Wesley, 1995, 1996, 1997
F. Buschmann, R. Meunier, H. Rohnert, P. Sommerlad, M. Stal: Pattern-Oriented Software Architecture—A System of Patterns, John Wiley and Sons, 1996
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 171
SE 1
References (2)
ReferencesM. Fowler: Analysis Patterns, Addison-Wesley,
1997
K. Beck: Smalltalk Best Practice Patterns, Prentice Hall, 1997
J.O. Coplien: Advanced C++ Styles and IdiomsAddison-Wesley, 1992
D. Lea: Concurrent Programming in Java, Design
Principles and Patterns, Addison-Wesley, 1997
J. Vlissides: Pattern Hatching, Addison-Wesley, 1998
The Patterns Home Page http://www.hillside.net/patterns/
The Jolt (Wash. U/Siemens Coop.) Home Page
http://www.cs.wustl.edu/~schmidt/patterns/
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 172
SE 1
Questions?
S
© Siemens AG, 1999Frank Buschmann
ZT SE 1
Page 173
SE 1
To Do List
To Do List• User Interface Design
– Telegram Office for Telegram Handling
– Abstract Factory for Telegram Creation and View Data Creation
– Composite and Chain of Responsibility for hierarchical Controllers
– Event Channel for Controller/View push notification upon telegram arrival
– Wrapper Facade for accessing GUI library
– View Handler for view management
– Sensors and Display for device adaptation
Other Ideas• Null Object for invalid commands.
• Extension Interface for system extensibility.
• Two-Level Commit for basic transaction control in the system.
Pattern Coverage• GOF: 12 of 23
• POSA1: 6 of 17
• POSA2: 5 of 17 (?)
• Other: 1