class User
attr_reader :name, :plan
def initialize(name:, plan:)
@name = name
@plan = plan
end
end
john_doe = User.new(name: 'John Doe', plan: 'Standard')
class Team
attr_reader :name
def initialize(name)
@name = name
end
end
finance = Team.new('Finance')
support = Team.new('Support')
class User
attr_reader :name, :plan, :observers
def initialize(name:, plan:)
@name = name
@plan = plan
@observers = [] # Store all observers in array
end
# After plan is changed we want to notify all observers
def plan=(plan)
@plan = plan
notify_observers
end
# Adding observers
def add_observer(observer)
@observers << observer
end
# Removing observers
def delete_observer(observer)
@observers.delete(observer)
end
# All observers from the list will be updated
def notify_observers
@observers.each { |observer| observer.update(self) }
end
end
class Team
attr_reader :name
def initialize(name)
@name = name
end
def update(user)
# Increase the amount, provide additional services,
# or do something else...
end
end
john_doe.add_observer(finance)
john_doe.add_observer(support)
# After plan is changed, Team update method will be triggered
john_doe.plan = 'Premium'