SW D A Lab Manual 11
SW D A Lab Manual 11
Spring 2022
The customer could visit the store every day and check prod-
uct availability. But while the product is still en route, most
of these trips would be pointless.
On the other hand, the store could send tons of emails (which
might be considered spam) to all customers each time a
new product becomes available. This would save some
customers from endless trips to the store. At the same
time, it’d upset other customers who aren’t interested in
new products.
It looks like we’ve got a conflict. Either the customer
wastes time checking product availability or the store
wastes resources notifying the wrong customers.
Solution
The object that has some interesting state is often called
sub- ject, but since it’s also going to notify other objects
about the changes to its state, we’ll call it publisher. All other
objects that want to track changes to the publisher’s state are
called sub- scribers.
Real-World Analogy
If you subscribe to a newspaper or magazine, you no
longer need to go to the store to check if the next issue is
available. Instead, the publisher sends new issues directly to
your mail- box right after publication or even in advance.
Structure
2. When a new event happens, the publisher goes over the sub-
scription list and calls the notification method declared in
the subscriber interface on each subscriber object.
Pseudocode
In this example, the Observer pattern lets the text editor
object notify other service objects about changes in its state.
Notifying objects about events that happen to other objects.
You could try the direct approach: unwrap all the boxes,
go over all the products and then calculate the total. That
would be doable in the real world; but in a program, it’s not as
simple as running a loop. You have to know the classes of
Products
Solution
The Composite pattern suggests that you work with Products
and Boxes through a common interface which declares a
method for calculating the total price.
Real-World Analogy
Structure
1. The Component interface describes operations that are com-
mon to both simple and complex elements of the tree.
Pseudocode
In this example, the Composite pattern lets you implement
stacking of geometric shapes in a graphical editor.
The geometric shapes editor example.
The client code works with all shapes through the single
inter- face common to all shape classes. Thus, the client
doesn’t
know whether it’s working with a simple shape or a com-
pound one. The client can work with very complex object
structures without being coupled to concrete classes that
form that structure.