The Observer Design Pattern in Ruby!!

Design patterns have always been a vital part of a quality software development. In fact, they let developers work in a team effectively by setting up the common ground rules for a problem.
In this post, I’d like to introduce you to The Observer Pattern. Basically, Observer is a behavioral type, or publish/subscribe pattern which allows a number of observer objects to see an event. So, if an observer object is subscribed to an event on the subject, on a change/update of that event on the subject will publish/reflect the changes on the observing objects as well.
For example, An electric bulb’s state(on/off) will depend on the state of the switch it is directly connected to. So, if I turn the switch on then the bulb will be turned on, and vice-a-versa.
Now, think switch and bulb as objects. These objects will have two states: either on or off. However, the bulb’s state will entirely depend on the switch’s state.

Bored reading theoretical stuff?? Let’s see some code in action:

The code above shows an Appliance class, which I thought makes more sense. Since we have a bulb, fan, A.C. which are ultimately electrical appliances which have different attributes(of course) except one, which is the state(on/off).

One thing you’ll notice when you see your switch is that, it is integrated on a switch box, so we do that in SwitchBox class. Later we integrate all switches in SwitchBox using Switch class.

Now, all we need is to run the code.

Just in case if you didn’t like something or wanna report an issue then here is the link to the code in the Github repository.


  1. Excellent knowledge, I am very much thankful to you that you have shared good information with us. Here I got some special kind of knowledge and it is helpful for everyone. Thanks for share it. test and tagging


Post a Comment

Popular posts from this blog

Why should I write tests?

How I started my career after graduation