ActionScript 3.0 Design Patterns

(Chris Devlin) #1
What Is the Observer Pattern? | 283

However, by using a single call to the web service and then broadcasting to the mul-


tiple instances, you need far fewer service calls.


In addition to being more efficient, a central data source guarantees that every


instance gets the same information. Imagine a change in data from one web service


call to the next where a major change occurs. The first instance calls the service and


formats the data into a table, and the second instance calls the service to format the


data in a bar chat. The data in the chart does not reflect the data in the table, even


though it’s supposed to. Using an Observer pattern, a single call to the web service


always sends data from the same callto all subscribers. So the data sent to the table


formatting instance and that sent to the charts is guaranteed to be from the same set.


In applications where a high rate of data change occurs, the Observer pattern helps


to cut down on the bookkeeping. All data are sent to a central source and then dis-


tributed to subscribing instances. For example, in an action game, the score keeps


changing as many game conditions rapidly update. When an object in an action


game is “destroyed,” it no longer needs the information and should not keep gather-


ing in data. Likewise, objects that come into the game or are “resurrected” need to


start getting data. This can be a programming nightmare without some kind of sys-


tem to take in all data changes and then uniformly distribute those changes to the


different game elements while taking care of all subscription changes. Here the


Observer pattern comes to the rescue by handling all data collection and


distribution.


Key Features


The central feature of the Observer pattern is that state change is gathered in one


place and sent to all subscribing units. This one-to-many relationship allows devel-


opers to create loosely coupled classes and yet maintain information consistency.


Figure 8-1 shows the general relationship between the initial data source, the subject


class, and the observer classes:


Sending information in this manner to different classes is not only efficient, but also


allows for expansion. For example, suppose stock data is subjected to different types


of statistical models, each one encapsulated in a class. As new analytical models are


Figure 8-1. Observer information flow


State change Subject

Observers
Free download pdf