I’m observing you!

Design patterns are reusable solutions to generally recurring problems that helps to solve them efficiently. These are the patterns that are observed in commonly occurring problems, and gives a well described solution to them. Observer pattern is one of the common patterns in the programming world.

What is it?

An observer pattern is a design pattern where a change in object is notified to other ‘interested’ objects. This essentially means changes in one object are notified to the objects who are subscribed to it. The subscribing objects are called observers, and the object who sends the notification is called the observable or the subject. The subject has knowledge of it’s observers.

Where do I see it?

Take an example of a Quora Post, which has many followers. As long as any person answers the question, all the followers are notified. Here, the post is the subject, and the followers are the observers. Another example can be of the website where you are going to buy your mobile phone, but it is out of stock. You give your email address to the website, asking to notify when the product gets available. The website notifying you on the mobile getting available is a classic example of the observer pattern.

How is it useful?

You can use observer pattern where you see one object getting affected because of a change in an another object, but we don’t want to couple both the objects together. Observer pattern is mainly used when there is a one to many relationship between the objects, and goes well in MVC frameworks where model changes are propagated to the view.

Let’s go back to the Mobile purchasing website scenario. Let’s say that the website shows mobile availability only when there is a sale, and since the user is registered with the website to get notification on the availability, they should be notified on the sale. Let’s take a look at the following implementation in Ruby.


class Website
 attr_reader :mobile_availability

 def initialize(user1, user2)
  @mobile_availability = false
  @user1 = user1
  @user2 = user2
 end

 def sale
  @mobile_availability = true
  @user1.update()
  @user2.update()
 end
end

class User
 def update
  puts "I can buy the phone now as it is available"
 end
end

user1 = User.new
user2 = User.new
website = Website.new(user1, user2)
website.sale

Now, the website here is very tightly bound to the users, and also takes up a lot of responsibility in updating other users. Hence, we can abstract this by adding two more methods to streamlining adding and notifying the observers.


class Website
 attr_reader :mobile_availability
 attr_accessor :observers

 def initialize()
  @mobile_availability = false
  @observers = []
 end

 def add_observer(observer)
  @observers << observer
 end

 def notify_observers
  @observers.each do |observer|
  observer.update(self)
 end
 end

 def sale
  @mobile_availability = true
  notify_observers
 end
end

website.add_observer(user1)
website.add_observer(user2)
website.sale

Again, this isn’t the ideal way to organize code, and we can take out the observer related methods to a different module.


module Subject
  def initialize
   @observers = []
  end

 def add_observer(observer)
  @observers << observer
 end

 def notify_observers
  @observers.each do |observer|
  observer.update(self)
  end
 end
end

class Website
 include Subject
 attr_reader :mobile_availability
 attr_accessor :observers

 def initialize
  super()
  @mobile_availability = false
 end

 def sale
  @mobile_availability = true
  notify_observers
 end
end

That’s it. We have separated out the observer methods to a module named Subject. Though the methods of the module are still included in the Website Object, and makes it the Website’s behavior, we still have a more maintainable and independent code.

Constraints

The primary drawback of the observer pattern is that objects tend to know each other, and have side effects. Notifications can become undependable and get us into race conditions. Besides, it adds an additional responsibility to the subject of notifying the observer.

Publish-Subscribe Pattern

Publish-Subscribe Pattern is a slight variant of the observer pattern where the subject doesn’t have the knowledge of it’s observers. In this pattern, senders of messages, called publishers, do not send the message directly to the registered observers, called subscribers, but instead characterize published messages into classes without knowledge of the subscribers. Usually, the message is sent to message queues, which are processed asynchronously. This ensures that the objects are loosely coupled, and are independent and reusable.

To implement Publish-Subscribe or the Pub-Sub Pattern pattern in Ruby, you can use the wisper gem (https://github.com/krisleech/wisper)Wisper is a micro library providing Ruby objects with Publish-Subcscribe capabilities.

That’s all. Hope, the observer pattern comes in handy to you. You can read more about observer pattern at http://www.oodesign.com/observer-pattern.html 

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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