Describe the technologies used in implementing disconnected business logic: COM+ queued components and loosely coupled events LCE!. Logical Design of Disconnected Business LogicThe purpo
Trang 1Demonstration: Queued Components 11
Logical Design of Disconnected Business
Trang 2to represent any real individual, company, product, or event, unless otherwise noted Complying with all applicable copyright laws is the responsibility of the user No part of this document may
be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Microsoft Corporation If, however, your only means of access is electronic, permission to print one copy is hereby granted
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property
2000 Microsoft Corporation All rights reserved
Microsoft, Active Directory, ActiveX, BackOffice, BizTalk, FrontPage, Microsoft Press, MSDN, MS-DOS, PowerPoint, Visio, Visual Basic, Visual C++, Visual InterDev, Visual J++, Visual Studio, Win32, Windows, and Windows NT are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A and/or other countries
Other product and company names mentioned herein may be the trademarks of their respective owners
Program Managers: Rhy Mednick, Susie Parrent
Instructional Designer: Susie Parrent
Subject Matter Experts: David Chesnut, Sam Gill (TechnoWiz), Michel Pahud
Media Management: David Mahlmann
Editing Manager: Lynette Skinner
Editor: Mick Alberts, Jennifer Linn
Production Manager: Miracle Davis
Print Coordinators: Linda Lu Cannon (Write Stuff), Marlene Lambert (Online Training
Solutions, Inc.)
Build Coordinator: Eric Wagoner
Graphic Artist: Scott Serna
Test Lead: Eric Myers
Manufacturing Manager: John Williams
Group Product Manager: Juan Fernando Rivera
Lead Product Manager, System Services and Infrastructure: Edward Dudenhoefer
Manufacturing Manager: Rick Terek
Operations Coordinator: John Williams
Manufacturing Support: Laura King; Kathy Hershey
Lead Product Manager, Release Management: Bo Galford
Group Manager, Courseware Infrastructure: David Bramble
General Manager: Robert Stewart
Trang 3Instructor Notes
In the preceding module, “Business Logic for Connected Components,” you introduced students to cooperative processing among synchronous business objects in an enterprise solution This module provides students with an introduction to cooperative processing among business components that are disconnected in time and space
After completing this module, students will be able to:
! Describe the design and implementation of disconnected business logic and how to apply design patterns to the design of business logic
! Describe the technologies used in implementing disconnected business logic: COM+ queued components and loosely coupled events (LCE)
! Create a physical design for a queued component
! Create a physical design for event notification
Materials and Preparation
This section provides the materials and preparation tasks that you need to teach this module
Required Materials
To teach this module, you need the following materials:
! Microsoft® PowerPoint® file 1910A_07.ppt
! Module 7: Business Logic for Disconnected Components
! Lab 7: Business Logic for Disconnected Components
Preparation Tasks
To prepare for this module, you should:
! Read all of the materials for this module
! Complete the lab
Presentation:
90 Minutes
Lab:
60 Minutes
Trang 4Demonstration
This section provides demonstration procedures that will not fit in the margin notes or are not appropriate for the student notes
Queued ComponentsTo prepare for the demonstration
• Review the instructions in the student notes
COM+ Events
• Review the instructions in the student notes
Trang 5Module Strategy
Use the following strategy to present this module:
! Introduction to Disconnected Business Logic The purpose of this section is to introduce students to the disconnected business logic layer The business needs of an application require its interaction with other business applications Frequently, these interactions can be separated in time and space Two business scenarios can summarize the business requirements for loosely coupled mechanisms:
• Response is never required The client’s job is complete when the call has been made and the message or notification is sent This model works well for applications whose only task is input
• Immediate response not required
In this scenario, the application does not require an immediate response but expects some form of acknowledgement at some time in the future
In the topic “The Business Problem,” illustrate disconnected business logic
by using SneakerNet as an example Point out that when using SneakerNet you can pass files but you don’t guarantee delivery Contrast this with using Message Queuing, where delivery is guaranteed
In the topic “Business Requirements,” illustrate the interaction with the following example If you are planning a trip from San Francisco to Tel Aviv, you can book your flight with Vigor Airlines (VA) and Blue Sky Airlines (BA) VA would be your carrier from San Francisco to London, and BA would be your carrier from London to Tel Aviv VA acts as your primary agent and can confirm your reservation on its flights but cannot confirm your reservations on BA VA can send a message to BA to ask for confirmation The BA system will subsequently confirm or deny your reservation and notify VA accordingly
! TechnologiesThe purpose of this section is to introduce students to Message Queuing, queued components, and COM+ events Spend time
demonstrating queued components and COM+ events and answering student questions about these two demonstrations
In the topic “Message Queuing,” continue using the VA/BA example to explain the operation of message queuing
! Logical Design of Disconnected Business LogicThe purpose of this section
is to introduce students to the two design patterns that can be used in the logical design of disconnected business logic: Observer and Queue
In the topic “Queued Components and Transactions,” explain the concept of
a transaction in a disconnected logic environment and the need for a compensating transaction You can use the example of VA and BA to explain that if BA returns a denial of a reservation you would need to add to the application a compensating transaction The compensating transaction would reverse the confirmation of a VA flight since it is no longer applicable if the connection from London to Tel Aviv cannot be made
Trang 6! Physical Design of Disconnected Business LogicThe purpose of this section
is to introduce students to the physical design considerations of COM+ events and queued components
! Market Purchasing The purpose of this section is to present the logical and physical designs of the disconnected business logic of Market Purchasing and to explain the justification for the choices made
By using the Computer Management application, you can present the mpVendors queue that is implemented by Market Purchasing You can also use Component Services to present the Market Purchasing Business Logic COM+ application By running the Monitor, Vendor, and Accounting applications, you can demonstrate how the disconnected logic works in Market Purchasing You can present the Extensible Markup Language (XML) files that are created when the accounting application is used Or you can show how the mpVendors queue receives messages when a vendor sends notifications
! Best Practices The main message presented in this section is to use the power of queues for disconnected business logic While events are important, the fact that you can only use them on-node makes them too restrictive
Lab Strategy
! Lab 7: Business Logic for Disconnected Components The purpose of Lab 7 is for students to learn to design disconnected business logic Students probably will not derive answers that correspond exactly to the Market Purchasing design This is acceptable as long as the student answers are justified and reflect the principles discussed in the module Discuss with students their answers to Lab 7
Trang 7# Overview
! Introduction to Disconnected Business Logic
! Technologies
! Logical Design of Disconnected Business Logic
! Physical Design of Disconnected Business Logic
! Market Purchasing
! Best Practices
In Module 6, “Business Logic for Connected Components,” you were introduced to cooperative processing among synchronous business objects in an enterprise solution In this module, the focus shifts to cooperative processing among business components that are disconnected in time and space
After completing this module, you will be able to:
! Describe the design and implementation of disconnected business logic and how to use design patterns
! Describe the technologies used in implementing disconnected business logic: COM+ queued components and loosely coupled events (LCE)
! Create a physical design for a queued component
! Create a physical design for event notification
In this module, you will learn
about the disconnected
business logic layer and
how to create a logical
design and a physical
design for it
Trang 8# Introduction to Disconnected Business Logic
! The Business Problem
! Business Requirements
Disconnected business logic allows logical business objects and physical business components to cooperate even though they are separated by time and perhaps space The temporal separation is called asynchronous behavior This behavior manifests itself in business logic that makes calls on other business logic objects and does not wait for the results
In this section, the disconnected business logic layer will be placed in the proper context of the business problem A discussion of the business requirements for disconnected business logic will follow
In this section, you will learn
what makes up a business
logic layer and, in particular,
a disconnected business
logic layer
Trang 9The Business Problem
Data Access Layer
Connected Business Logic Layer
Disconnected Business Logic Layer
Facade Layer Web Services Facade Business Facade
Transactional DAL Nontransactional DAL
User Services
External Objects
There are many parts of a system that can be disconnected, or asynchronous Asynchronous requirements must be identified early, and the design must take them into account
Asynchronous Behaviors
Many aspects of a distributed system do not need to be synchronous For example, consider an order being placed by a customer When the customer clicks a button to enter the order, the business logic needs to save the order to a database to record the purchase The business logic also must send the order to the shipping department to ship the goods on the order to the customer
However, the customer is not expecting that the order be shipped immediately, nor does the customer need to be aware of how the order is handled internally
by the system The only synchronous response expected by the customer is that the order be placed successfully Consequently, the order does not need to be sent to the shipping department immediately It could be placed in a queue until the shipping department gets a chance to process the order
Sometimes a system requires asynchronous behavior For example, when a requisition is entered into the Market Purchasing sample application, the requisition is saved If the requisition is greater than a certain amount, it requires manager approval Because no manager can be expected to monitor the system 24 hours a day, the approval must wait until the manager logs on to the Market Purchasing application This behavior is by nature asynchronous and requires disconnected business logic to be implemented
Topic Objective
To provide background
about the business problem
Lead-in
In this topic, you will learn
about the business problem
facing designers that need
to implement a business
logic layer
Trang 10Disconnected Business Logic Layer
The solution to dealing with asynchronous behavior is to create a disconnected business logic layer The disconnected business logic layer is parallel with the connected business logic layer In other words, the facades call both layers, and each layer uses the data access layer (DAL)
The disconnected business logic layer receives requests from the business or Web services facade layer, processes the requests, and passes additional processing to external objects The disconnected business logic components must also implement techniques for retrieving the results from the external objects and pass the results of the processing back to the facade layer
Trang 11Business Requirements
! Asynchronous Communication and Notification
! Messaging and Events
In an enterprise solution, communication or notification between business objects that reside on different nodes that use synchronous protocols might not always be the best solution:
! The lifetimes of client and server cannot always be guaranteed to overlap
! The network connection that links client to server cannot always be guaranteed to be working
! The network latency associated with the wide-area connection cannot be predicted
As an alternative to synchronous communication or notification, consider the approach of using asynchronous communications based on messages or notification based on events With either approach, business objects on different nodes communicate with one another by passing messages or events through a third party messaging service or a notification service The interaction between business objects is mitigated through a third party that ensures delivery
In this enterprise solution scenario, message-based communication eliminates the need for the client to wait for the server’s response The client simply calls the server by sending it a message and then continues with other processing The message is stored in a holding area or queue until the receiver is ready to process it Similarly, event-based notification eliminates the need for the listener to be active when the event occurs
Asynchronous mechanisms are sometimes referred to as loosely coupled
because various pieces of the process are independent of one another
Additionally, the client and server might have independent lifetimes
In this topic, you will learn
about the business
requirements for a
disconnected business logic
layer
Trang 12Two business scenarios can summarize the business requirements for loosely coupled mechanisms:
! Response is never required The client’s job is complete when the call has been made and the message
or notification is sent This model works well for applications whose only task is input
! Immediate response not required
In this scenario, the application does not require an immediate response, but
it expects some form of acknowledgement in the future The application might only require negative acknowledgements indicating that some error has occurred, or it might require both positive and negative
acknowledgements In either case, a separate asynchronous communication can occur from the server to the client The primary benefit of using asynchronous communication or notification in this scenario is that end users do not need to wait for a response if it is not required (The response might take time given potential network latency or server unavailability.)
Trang 13# Technologies
! Message Queuing
! Queued Components
! COM+ Events
! Combining Queued Components and Events
In this section, you will learn about the Microsoft® technologies that can be used to implement disconnected business logic First, you will learn about Microsoft Message Queuing, which allows you to create queues to send and receive messages Second, you will learn about queued components, which allow you to call components while disconnected from them Third, you will learn about COM+ events for sending notifications and events Finally, you will learn how to combine queued components and events for sending notifications
In this section, you will learn
about the Microsoft
technologies that can be
used to implement
disconnected business
logic
Trang 14Message Queuing
! Supports Creating and Managing Queues
! Supports Sending and Receiving Messages to Queues
! Can Program Through API or COM Objects
Message Queuing is a rich set of run-time services that allow applications on different computers to send and receive asynchronous messages An object creates a message and sends it to a queue Another object can read the message from the queue The queue is a persistent storage area As soon as the message has been posted to the queue, the sending object can continue with other work without waiting for the message to be read
You use Message Queuing through an application programming interface (API) By using the API, you can programmatically create queues, send messages, receive messages, wrap messages in transactions, and secure messages You can also use a set of Component Object Model (COM) objects called the MSMQ COM Components, which wrap the API The MSMQ COM Components simplify the API and allow you to send messages by using almost any programming language For more information about building applications
that use Message Queuing, see Course 1901A: Building MSMQ Applications
In this topic, you will learn
about the features of
Message Queuing
Delivery Tip
You might want to remind
students that Message
Queuing was formerly
referred to as Microsoft
Message Queue Server
(MSMQ)
Trang 15Queued Components
The COM+ Queued Components service builds upon the Messaging Services infrastructure A client application creates a queued component in the same way that it would any other component The queued component exposes a COM interface that looks similar to any other COM interface The client is free to call methods on this interface in the same way as it would for a regular COM interface The main difference arises from the underlying communications mechanism used to deliver the method parameters With queued components, the communication between the client-side proxy and the server-side stub is handled by Messaging Services
Using COM+ Queued Components offers three advantages over directly using Messaging Services:
! Higher level of abstraction
! Conventional component behavior
! Choice of communication method The COM+ queued component architecture is represented by three objects: a
Recorder, a Listener, and a Player
The Recorder Object
The Recorder object is provided by the COM+ Queued Component service and
is conceptually similar to a standard COM proxy The Recorder object
provides an implementation for all of the methods in the object’s interface
However, the actual implementation is quite different The Recorder object’s
implementation for each method accepts the input parameters and, rather than firing them directly at the actual COM objects, records them into a message This process is repeated for each method call made by the client When the client deactivates the object, the COM+ Queued Component service uses Messaging Services to send the message containing the recorded calls to the server on which the actual COM object resides
Topic Objective
To provide a review of
queued components
Lead-in
In this topic, you will learn
about the physical design
issues for queued
components
Trang 16The Listener and Player Objects
When the message arrives at the server, the recipient application uses a
Listener object provided by the system to detect the inbound message
Messaging Services are then used to read the message, and a Player object is activated The Player object creates the actual COM object and plays the
recorded calls into it If the server application is not active when the message arrives, the message will be stored in the application’s queue When the application is subsequently started, it can retrieve and process any awaiting messages
Trang 17Demonstration: Queued Components
This demonstration includes a Microsoft Visual Basic® client, OrderClient,
that places an order consisting of first name, last name, address, and product ID
to a queued component The queued component, called qcOrder, will display a
message box indicating that it received the order after it is started
To run this demonstration, execute the following steps:
1 On the Start menu, point to Programs, then point to Administrative
Tools, and then click Component Services
2 In the left pane, expand Component Services, Computers, My Computer, and COM+ Applications
3 Right-click COM+ Applications, point to New, and click Application
4 In the Welcome to the COM Application Install Wizard dialog box, click
Next
5 Click the Create an empty application button
6 In the text box next to the label Enter a name for the new application, enter the name Orders, and then click Next
7 In the Set Application Identity dialog box, click Next
8 Click Finish
9 Select the Orders COM+ application
10 Right-click Orders and click Properties
11 Click the Queuing tab
12 Select the Queued and Listen check boxes and click OK
Topic Objective
To provide a demonstration
of queued components
Lead-in
In this demonstration, you
will see how to use queued
components in an
application
Trang 18! Install a Queued Component
1 In the left pane, expand Orders and Components
2 Right-click Components, point to New, and click Component
3 In the Welcome to the COM Component Install Wizard dialog box, click
Next
4 Click Install new component
5 In the Select files to install dialog box, select the file qcOrder.dll from the
directory install folder\Democode\Mod07\qcOrder and click Open
6 Click Next in the Install New Components dialog box
7 Click Finish
8 Expand the folders Orders, Components, qcOrder.Order, and Interfaces
9 Select the _Order interface
10 Right-click the _Order interface and click Properties
11 Click the Queuing tab
12 Select the Queued check box and click OK
1 On the Start menu, point to Programs, then point to Microsoft Visual
Studio 6.0, and then click Microsoft Visual Basic 6.0
2 In the folder install folder\Democode\Mod07\OrderClient, open the Visual
Basic project OrderClient.vbp
3 Run the OrderClient application
4 Enter a First Name, Last Name, Address, and Product ID Then click the
Place Order button
5 On the Start menu, point to Programs, then point to Administrative
Tools, and then click Computer Management
6 In the Computer Management application, expand Services and
Applications, Message Queuing, Public Queues, and orders
7 Right-click the Queue messages folder and click Refresh The right pane
should indicate that there is one message waiting in the orders queue This message was created by the recorder for the OrderClient application placing
an order
1 Return to the Component Services snap-in
2 Select the Orders COM+ application
3 Right-click Orders and click Start A message box should appear with the details of the order Dismiss the message box by clicking OK
4 Return to the Computer Management application
5 Right-click the orders queue and click Refresh The right pane should
indicate that there are no messages waiting The message was delivered to the queued component
Trang 19COM+ Events
Events in COM+ are based on an LCE model The loose coupling is achieved
by introducing an intermediary between publisher and subscriber—namely, the COM+ event service The COM+ event service matches event subscribers with event publishers The event service maintains a database that lists subscribers for a particular class of event A subscriber wanting to subscribe to a particular class of event contacts the event service, which adds a subscription record to the database When a publisher wants to fire an event, the publisher talks to the event service The event service searches the subscription database, contacts each of the subscribers in turn, and forwards the event
The publisher and subscriber architecture adopted by the COM+ Event Service uses two components First, an event class is used to represent the connection between a publisher and a subscriber Second, the COM+ Event Store within the COM+ Catalog is used as a database for subscriptions
The Event Class
The event class is a COM+ component that contains the interfaces and methods used by a publisher to fire events The event class is abstract in nature Its purpose is to define one or more COM interfaces that define a set of events that can be fired
In this topic, you will learn
about the physical design
issues for loosely coupled
events of a COM+ object
Trang 20The COM+ Event Store
The COM+ Event Store maintains a subscription list Subscribers place entries
in the event store either by using the Component Services administration tool or programmatically by using the COM+ administration interfaces A subscription record provides the event service with information about the recipient of an event There are three types of subscription supported by the COM+ Event Service:
! Persistent Persistent subscriptions reside in the COM+ Event Store and survive system restarts
! Transient Transient subscriptions are tied to a particular object instance Transient subscriptions are maintained in the Event Store, but they do not survive system restarts
! Per User Per User subscriptions can only deliver events when the subscriber is logged into the event system’s computer When the subscriber logs off, the
subscriptions are disabled
When an event fires, the event store is accessed, and each subscriber in the list
is contacted COM+ forwards the event from the publisher to each subscriber Subscribers do not have to be running when an event is fired The COM+ Event Service will create instances of each subscriber component
Filtering Events
Filtering events allows subscribers to be more selective with regard to the events they receive It also allows publishers to control exactly which subscribers should receive events and the order in which the subscribers should receive the events
Trang 21Demonstration: COM+ Events
The demonstration of COM+ events includes two Visual Basic COM
components The first is eTicker, which has two functions, Up and Down, that have no implementations, and the second is subTicker, which provides the implementations for both Up and Down The demonstration also includes a test application, eTickerDemo
These components demonstrate a scenario in which a stock price monitor
(eTickerDemo) can generate events when stock prices move up or down The event class (eTicker) is implemented by subscribers (subTicker) to receive
notifications when a stock price moves This demonstration also shows how to filter events To run this demonstration, complete the following steps:
1 On the Start menu, point to Programs, then point to Administrative
Tools, and then click Component Services
2 In the left pane, expand Component Services, Computers, My Computer, and COM+ Applications
3 Right-click COM+ Applications, point to New, and click Application
4 In the Welcome to the COM Application Install Wizard dialog box, click
Next
5 Select Create an empty application
6 In the Create Empty Application dialog box, enter eTicker as the new application name and then click Next
7 In the Set Application Identity dialog box, click Next
8 Click Finish
9 In the left pane, expand eTicker and Components
10 Right-click Components, point to New, and click Component
11 In the Welcome to the COM Component Install Wizard dialog box, click
In this demonstration, you
will see how to use COM+
events in an application
Trang 2212 Click Install new event class
13 In the Select files to install dialog box, select the file eTicker.dll from the
directory install folder\Democode\Mod07\eTicker and click Open
14 Click Next, and then click Finish
1 Right-click COM+ Applications, point to New, and click Application
2 In the Welcome to the COM Application Install Wizard dialog box, click
Next
3 Select Create an empty application
4 In the Create Empty Application dialog box, enter subTicker as the new application name, and then click Next
5 In the Set Application Identity dialog box, click Next
6 Click Finish
7 In the left pane, expand subTicker and Components
8 Right-click Components, point to New, and click Component
9 In the Welcome to the COM Component Install Wizard dialog box, click
Next
10 Click Install new component
11 In the Select files to install dialog box, select the file subTicker.dll from the
directory install folder\Democode\Mod07\subTicker and click Open
12 Click Next, and then click Finish
1 In the left pane, expand subTicker.SubDemo and Subscriptions
2 Right-click Subscriptions, point to New, and click Subscription
3 In the Welcome to the COM New Subscription Wizard dialog box, click
Next
4 Select the _Move interface and click Next
5 In the Select Event Class dialog box, select the event class eTicker.Move and click Next
6 In the Subscription Options dialog box, enter the name All Events for the subscription and select the Enable this subscription immediately box Click Next, and then click Finish
7 Right-click Subscriptions, point to New, and click Subscription
8 In the Welcome to the COM New Subscription Wizard dialog box, click
Next
9 Select the method Down and click Next
10 In the Select Event Class dialog box, select the event class eTicker.Move and click Next
11 In the Subscription Options dialog box, enter the name Down only for the subscription and select the Enable this subscription immediately box Click Next, and then click Finish
Trang 23! Adding a filter
1 In the left pane, expand subTicker and Subscriptions
2 Right-click All Events and click Properties
3 Click the Options tab, and in the Filter criteria field, enter ticker
!="INTC"
4 Click OK
1 On the Start menu, point to Programs, then point to Microsoft Visual
Studio 6.0, and then click Microsoft Visual Basic 6.0
2 In the folder install folder\Democode\Mod07\eTickerDemo, open the Visual
Basic project eTickerDemo.vbp
3 Run the application eTickerDemo
4 Enter a ticker symbol MSFT and click Down
You should see two message boxes displaying the message “MSFT has
moved down.” There is one message for each subscription
The message boxes might appear behind other windows If this
happens, a task will appear on the taskbar called subTicker You can select the subTicker task to display the message box
5 Enter a ticker symbol INTC and click Up
You should not get any message box The INTC ticker symbol is filtered in
All Events
Note
Trang 24Combining Queued Components and Events
You can combine the COM+ Event service with the Queued Component service to make the publisher and subscriber achieve temporal independence You can publish events asynchronously (queuing between publisher and event)
or you can deliver events asynchronously (queuing between event and subscriber)
To publish events asynchronously, you must introduce a queuing mechanism between the publisher and event object To facilitate this process, you make the event object a queued component
To deliver events asynchronously, you must introduce a queuing mechanism between the event object and the subscriber To facilitate this process, you make the subscriber a queued component and instruct COM+ to deliver events
to subscribers asynchronously by using Messaging Services
In this topic, you will learn
about the physical design
issues involved in combining
the two asynchronous
mechanisms of a COM+
object
Trang 25# Logical Design of Disconnected Business Logic
! Observer
! Queue
! Queued Components and Transactions
In this section, the following design patterns that apply to the logical design of a disconnected business logic layer will be presented: Observer and Queue
In addition to the two design patterns covered in Module 6, “Business Logic for Connected Components” (Iterator and State), the disconnected business logic layer can use two behavioral design patterns: Observer and Queue
An Observer behavioral design pattern defines a one-to-many dependency among objects such that when one object changes state all of its dependents are notified Depending on whether notification happens automatically, an
Observer design pattern can be mapped either to events or to Extensible Markup Language (XML) data structures, as you will see in detail in the following topics Observer objects are typically used in an enterprise solution when there is a publisher with one or more subscribers waiting for a particular event to occur
A Queue behavioral design pattern defines a many-to-many dependency between objects so that one or more objects post messages to a message queue and all of their dependents can retrieve the messages from the same message queue Queue objects are used in enterprise solutions that require decoupling of requests for a business service from multiple service providers that can handle a request independent of the source for the request For example, requesting fund allocation for a requisition can be handled by a number of accounting services providers
In this section, you will learn
about the logical design for
disconnected business
logic
Trang 26Observer
+Attach() +Detach() +Notify()
Subject
+Update()
Observer
+GetState() +SetState() -SubjectState
ConcreteSubject
+Update() -ObserverState
Pattern element Description
Pattern name Observer
Problem There exists a one-to-many dependency between objects such that multiple objects depend on
asynchronous notifications from one object
Solution Create a subject class that encapsulates the behavior of the object that will send notifications
Create an observer class that encapsulates the behavior of the objects that will receive notifications The observer class can begin receiving notifications by attaching itself to the
subject through the Attach method It can also stop receiving notifications by calling Detach
In general, when a concrete subject changes state, it calls the Notify method in the subject class, which then calls the Update method on all attached observer objects Each object will then call GetState on the concrete subject to determine the new state SetState can also be
used to change the state of the concrete subject
When to use Use the Observer design pattern:
• When a change to one object will require changing other objects and the number of objects that will be changed is unknown
• When an object is loosely coupled with the objects that need to receive notifications from it For example, a component that monitors stock prices
Benefits You can use the publish-subscribe model A notification from the subject (publisher) does not
need to specify who the observer (subscriber) is Consequently, new observers can be added or removed, even dynamically at run time
Drawbacks Notifications can cause cascading updates If an observer changes the subject state, updates are
sent out, which can cause other observers to again change the subject state As a result, the subject can go through several state changes with many updates as a result of one initial change Dependencies between the subject state and observers must be well defined and managed
In this topic, you will learn
about the application of the
Observer design pattern to
disconnected business
logic
Trang 27For more information on the Observer pattern, see the book Design Patterns:
Elements of Reusable Object-Oriented Software
As an example of the Observer pattern, consider an auction site where multiple bidders are placing bids on items When a new bid is posted, all of the other bidders must be notified of the change in the bid This activity is asynchronous because the new bids can be placed at any time The Observer pattern would be
a useful pattern to apply in this example
Trang 28Queue
+Store() +Retrieve()
Queue
+PostMessage() +Open() +Close()
-QueueID
Sender
+GetMessage() +Open() +Close()
In a Queue pattern, the senders do not know their receivers The senders provide a message that contains all of the information that the receivers need to act and achieve consistency
Pattern element Description
Pattern name Queue
Problem There exists a many-to-many dependency between objects such that one or more objects need
to communicate with other objects in an asynchronous manner
Solution When you partition a system into a collection of cooperating classes, you need to convey
information asynchronously from one or more classes to another set of classes (which could be the same as the original set) to maintain consistency between them You do not want to achieve consistency by coupling the classes because that reduces their reusability
First, a queue resource must be represented The Queue class represents the queue resource and exposes the methods Store and Retrieve The Store method will store a message in the queue, while the Retrieve method will retrieve a message from the queue
A sender will use the ConcreteSender class to send messages The sender will call the Open
method to open a queue resource and identify the queue by using QueueID Then the sender
can send messages by using the PostMessage method The sender will close the queue by calling Close
A receiver will use the ConcreteReceiver class to receive messages The receiver will call the
Open method to open a queue resource and identify the queue by using QueueID Then the
receiver will receive messages by using the GetMessage method The receiver will close the queue by calling Close
In this topic, you will learn
about the application of the
Queue design pattern to
disconnected business
logic
Trang 29Pattern element Description
When to use Use the Queue design pattern:
• When an abstraction has two aspects, one dependent on the other Encapsulating these aspects in separate objects lets you vary and reuse them independently
• When a change to one or more objects requires changing multiple other objects, and you do not know how many objects need to be changed
• When objects should be able to send messages to other objects without making assumptions about what these objects are In other words, you do not want these objects coupled
Benefits Abstract coupling between sender and receiver All that a sender knows is that it has a queue
All that a receiver knows is that it has a queue Consequently, the coupling between senders and receivers is abstract and minimal
Support for broadcast communication When a sender posts a message, all interested receivers can retrieve the message
Drawbacks Sporadic consistency Because a sender does not know its receiver, there is no guarantee that
the receiver will see the message to achieve timely consistency
For more information about the Queue pattern, see Appendix B: “Additional Design Patterns Used in Market Purchasing.”
Trang 30Queued Components and Transactions
The preceding slide shows how queued components participate in a transaction
on both the client and the server The slide shows two distinct transactions: one
on the client side and the other on the server side Message Queuing guarantees the delivery of the message from client to server It is important to be aware, however, that if the server-side transaction aborts, it does not affect the client-side transaction
When creating the logical design, you should ensure that any components sending or receiving messages by means of a transactional queue are obeying these semantics A common design misconception is to design a component such that when it sends the message, a successful transaction assumes the message was received by the receiving component The actual semantics are that sending the message under a successful transaction places the message in the queue It does not mean that the message was received and processed properly A separate transaction handles the receipt of the message
If a client must determine that the message was received and processed properly, you must design compensating transactions into the system The client would send the message and commit the transaction and assume the best If the server later reads the message and cannot process the message, and
consequently aborts its transaction, it must then send a message back to the client indicating that its transaction failed A compensating transaction would then be invoked to undo the original client transaction
In this topic, you will learn
how queued components
participate in transactions
on both the client and the
server
Trang 31Queued Components
Because queued components are built on Message Queuing, and Message Queuing is a resource manager that can participate in a transaction, queued components can also participate in transactions For example, if a transactional component makes changes to a database and queues messages to other
components, both operations are enlisted in the same transaction This means either that both operations will succeed or that both will fail If the transaction commits, the database changes become permanent and the outgoing messages are sent If the transaction aborts, the database changes are rolled back and the messages are discarded
In the case of a transactional component receiving inbound messages from Message Queuing and making database updates, if the transaction aborts, then the messages remain in the queue and the database changes are discarded If the transaction commits, the messages are removed from the queue and the
database changes are made permanent
On the client side, the Recorder object assumes the same transactional attribute
as the client On the server side, the message queue is protected by a transaction, so when read operations are performed, they are performed in a nondestructive manner As a result, if the transaction aborts, the messages remain in the queue