Observer Pattern
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 92 of 110.
The Observer pattern establishes a one-to-many relationship between objects: when one object (the subject) changes state, all its dependents (observers) are automatically notified. This is perfect for scenarios like UI updates, event systems, or any situation where multiple parts of your application need to react to changes.
The pattern involves two key roles: a Subject that maintains a list of observers and notifies them of changes, and Observers that register themselves and respond to updates:
abstract class Observer {
void update(String message);
}
class NewsAgency {
final List<Observer> _observers = [];
String _latestNews = '';
void subscribe(Observer observer) {
_observers.add(observer);
}
void unsubscribe(Observer observer) {
_observers.remove(observer);
}
void publishNews(String news) {
_latestNews = news;
for (var observer in _observers) {
observer.update(_latestNews);
}
}
}
class NewsChannel implements Observer {
final String name;
NewsChannel(this.name);
@override
void update(String message) {
print('$name received: $message');
}
}
void main() {
var agency = NewsAgency();
var cnn = NewsChannel('CNN');
var bbc = NewsChannel('BBC');
agency.subscribe(cnn);
agency.subscribe(bbc);
agency.publishNews('Breaking news!');
// CNN received: Breaking news!
// BBC received: Breaking news!
}When publishNews is called, the agency iterates through all subscribed observers and calls their update method. Observers can subscribe or unsubscribe at any time, making the system flexible and loosely coupled - the subject doesn't need to know the specific types of its observers.
Challenge
EasyLet's build a stock price alert system using the Observer pattern! You'll create a system where a stock ticker notifies multiple investors whenever the price changes, allowing each investor to react to market updates in their own way.
You'll organize your code into two files:
stock_system.dart: Create your observer system here:- An abstract class
Investorwith a methodvoid onPriceChange(String stockName, double price) - A class
DayTraderthat implementsInvestor. It has anamefield and itsonPriceChangemethod prints:[name] sees [stockName] at $[price] - Making quick trade! - A class
LongTermInvestorthat implementsInvestor. It has anamefield and itsonPriceChangemethod prints:[name] notes [stockName] at $[price] - Holding steady. - A class
StockTicker(the subject) with:- A
String stockNamefield - A private list to store subscribed investors
- A
subscribe(Investor investor)method to add an investor - An
unsubscribe(Investor investor)method to remove an investor - An
updatePrice(double newPrice)method that notifies all subscribed investors of the new price
- A
- An abstract class
main.dart: Import your stock system and demonstrate the Observer pattern in action:- Create a
StockTickerfor a stock namedDART - Create a
DayTradernamedAliceand aLongTermInvestornamedBob - Subscribe both investors to the ticker
- Update the price to
150.50(both investors should be notified) - Print an empty line
- Unsubscribe Alice from the ticker
- Update the price to
155.75(only Bob should be notified now)
- Create a
This demonstrates how the Observer pattern creates a loosely coupled system - the StockTicker doesn't need to know whether it's notifying day traders or long-term investors, it just calls onPriceChange on whoever is subscribed!
Expected output:
Alice sees DART at $150.5 - Making quick trade!
Bob notes DART at $150.5 - Holding steady.
Bob notes DART at $155.75 - Holding steady.Cheat sheet
The Observer pattern establishes a one-to-many relationship where a subject notifies all its observers when its state changes.
The pattern has two key roles:
- Subject: Maintains a list of observers and notifies them of changes
- Observer: Registers with the subject and responds to updates
Basic implementation:
abstract class Observer {
void update(String message);
}
class Subject {
final List<Observer> _observers = [];
void subscribe(Observer observer) {
_observers.add(observer);
}
void unsubscribe(Observer observer) {
_observers.remove(observer);
}
void notifyObservers(String data) {
for (var observer in _observers) {
observer.update(data);
}
}
}
class ConcreteObserver implements Observer {
final String name;
ConcreteObserver(this.name);
@override
void update(String message) {
print('$name received: $message');
}
}Key benefits:
- Loose coupling between subject and observers
- Observers can subscribe/unsubscribe dynamically
- Subject doesn't need to know specific observer types
Try it yourself
import 'stock_system.dart';
void main() {
// TODO: Create a StockTicker for a stock named 'DART'
// TODO: Create a DayTrader named 'Alice'
// TODO: Create a LongTermInvestor named 'Bob'
// TODO: Subscribe both investors to the ticker
// TODO: Update the price to 150.50 (both investors should be notified)
// TODO: Print an empty line
// TODO: Unsubscribe Alice from the ticker
// TODO: Update the price to 155.75 (only Bob should be notified now)
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor