Dennis’s Weblog

Observer Pattern – Design Patterns

Posted on: October 5, 2008

OO Principles :

  1. Encapsulate what varies.
  • vary1: The number of observers may change.  === use Composition and interface to encapsulate this change
  • vary2: The number of subject ‘s states may change. ===

          a. You can pull or push the data. === pull: use the get***() method to get the data.  push: the publisher send the data via function parameters: update(object ***);

          update(observerable o, object arg); (use such method you can utilize push and pull at the same time. o is the sender of message, and arg is the message. You can directly get the message from arg, or use the get***() methods of o the retrieve the information you want.

    2.Favor composition over inheritance.

       The Observer Pattern use composition to compose any number of observers with their subjects, These relationship aren’t set up by some kind of inheritance hierarchy, NO! They are set up at runtime by composition.

    3.Program to interfaces, not implementations.

    4.Strive for loosely coupled design between object that interact.

When two objects are loosely coupled, they have little knowledge about each other.

Then only one thing the subject know about the other is that it implements a certain interface.

We can add observers at any time.

We never need to modify the subject to add new types of observers.

we can reuse subjects and observers indepentently  of each other.

Changes to either subjects or observers will not affect the other.

Loosely coupled design allows us to design flexible OO systems that can handle changes because they minimize the interdependency between objects.

The subjects and observers connect upon interface, which use composition. In observers , they (has a)(dependency) subject, and subjects only know the knowledge about the interface, and call the method in the interface with aware of the implementation of the interface. 

Observer Pattern:

    Designs a one to many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Java buildin Observer Pattern:

java.util.observerable          a class                a interface

Make use of these two struct can help you. But there are also dark side!

ActionListener & EventHandler , they are all use observer pattern.


    Patterns just make well use of the OO principles!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: