design patterns: observer pattern

Post on 13-Apr-2017

139 Views

Category:

Software

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Design Patterns in Ruby

Observer Pattern

Copyright 2016. Jyaasa Technologies. All Right Reserved

http://jyaasa.com

Neha SuwalAssociate Software Engineer at Jyaasa Technologies

Design Patterns

Design principles are core abstract principles which we are supposed to follow while designing software architect

Observer Pattern:● one object to inform other ‘interested’ objects when its state changes

The Observable module in the Ruby standard library provides the mechanism necessary for us to implement this pattern, and it is fairly easy to use.

Example:module Email extend self

def send(subject, receiver) mail to: “#{receiver}@example.com”, subject: “#{subject}” endend

class Person include Email attr_reader :name

def initialize(name) @name = name end

def send_email(subject, receiver) Email.send(subject, receiver) endend

bill = Person.new 'Bill'bill.send_email 'Fishing Trip', 'Fred'

class Alert def gotcha(person) puts "!!! ALERT: #{person} SENT AN EMAIL !!!" endend

module Subject attr_reader :observers

def initialize @observers = [] end

def add_observer(*observers) observers.each { |observer| @observers << observer } end

private def notify_observers observers.each { |observer| observer.gotcha(self) } endend

class Person include Email, Subject attr_reader :name

def initialize(name) # 'super' requires a parentheses because we're calling # super on the superclass, 'Subject' super() @name = name end

def send_email(subject, receiver) Email.send(subject, receiver) notify_observers endend

alert = Alert.new

bill = Person.new 'Bill'

bill.add_observer alert

bill.send_email 'Fishing Trip', 'Fred' !!! ALERT: BILL SENT AN EMAIL !!!

THANK YOU!

top related