Behavioral pattern 2026-10-31
A software design pattern concerned with allocating behavior and communication responsibilities among objects. Observer patterns notify dependents, while a command pattern represents a request as an object.
Model-view-controller 2026-10-31
Separate an application's domain state and rules into a model, its presentation into a view, and interpretation of user actions into a controller. The controller requests model operations; the view renders coherent model state. A playlist model, for example, owns song order independently of whether a menu, button or keyboard action requests a move. The Observer pattern often carries model-change notifications to views, but model-view-controller defines responsibilities rather than requiring a particular notification mechanism. This supports separation of concerns and testing domain logic independently of a graphical interface.
In model-view-controller, the model owns application data and its rules: here it is the ordered
DataList with its uniqueness condition on horizontal coordinates. A view renders those data, for example as a line plot or a bar plot. View-specific decisions such as whether to show axes need not change the model. A controller interprets actions such as entering a new sample or selecting a plot style, and requests the appropriate model or view operation.This separation of concerns permits several views of the same data and allows model operations to be tested without drawing a window. When the model changes, affected views need a notification or another refresh mechanism. The Observer pattern in part (d) supplies one such mechanism, without making the model depend on every concrete view software class. The division is
In the Observer pattern, an observable subject keeps registered observers behind a shared object interface. After a relevant update, the subject calls that object interface on each observer. Observers can register and unregister independently, and the subject needs no knowledge of their concrete software classes.
For this model-view-controller application,
DataList is the subject, while graph views are observers. After a successful insertion, a notification tells each registered view to redraw from the updated model. An invalid insertion leaves the model unchanged and needs no change notification. Calling observers only after restoring the representation invariant prevents views from seeing a half-completed insertion. HenceKeep storage private. Find the first entry whose horizontal coordinate is not smaller than the new one. Equality there means that the coordinate is already present; otherwise insertion at that position preserves strict ordering. Reject nonfinite coordinates, since a
NaN would make the required comparisons meaningless. This is an explicit finite-coordinate contract for a display application.[ref]Java 8 Double API documentation. isFinite(double)
The Observer pattern uses a small callback Java interface. With
import java.util.*;, the full implementation is:interface GraphObserver {
void changed(DataList source);
}
final class DataList implements Iterable<Point> {
private final List<Point> points;
private final List<GraphObserver> observers;
public DataList() {
points = new ArrayList<Point>();
observers = new ArrayList<GraphObserver>();
}
public void addObserver(GraphObserver observer) {
if (observer == null)
throw new IllegalArgumentException("null observer");
for (GraphObserver old : observers)
if (old == observer) return;
observers.add(observer);
}
public void removeObserver(GraphObserver observer) {
for (int i = 0; i < observers.size(); ++i) {
if (observers.get(i) == observer) {
observers.remove(i);
return;
}
}
}
public void addPoint(double x, double y) throws Exception {
if (!Double.isFinite(x) || !Double.isFinite(y))
throw new Exception("nonfinite coordinate");
int i = 0;
while (i < points.size() && points.get(i).getX() < x) ++i;
if (i < points.size() && points.get(i).getX() == x)
throw new Exception("duplicate x coordinate");
points.add(i, new Point(x, y));
List<GraphObserver> current =
new ArrayList<GraphObserver>(observers);
for (GraphObserver observer : current) observer.changed(this);
}
public Iterator<Point> iterator() {
List<Point> snapshot = new ArrayList<Point>(points.size());
for (Point p : points) snapshot.add(p.clone());
return Collections.unmodifiableList(snapshot).iterator();
}
}This is a sequential implementation. Callback object methods are required to return normally and not reenter
addPoint; they may change their registrations. Copying the registration list means such changes affect future notifications, while each observer present at the start of this notification gets exactly one call. Repeated registration of the same observer is ignored by object identity. Both signed zeros compare equal and therefore count as the same horizontal coordinate.For correctness, all old entries before position
i have smaller horizontal coordinates. If an entry at i exists after the duplicate check, it has a strictly larger coordinate. Inserting between these two groups preserves the representation invariant; rejecting a duplicate has no state effect. No client receives a stored mutable Point. ThusCreational patterns organize object creation; behavioral patterns organize interactions and responsibility for behavior. A creational pattern controls how concrete software objects are selected, instantiated, or shared, so clients need not hard-code the entire construction policy. Examples include the factory method pattern and the singleton pattern.
A behavioral pattern describes how objects collaborate, receive requests, or distribute an algorithm's behavior. For example the observer pattern lets a subject notify dependants after its state changes, and the strategy pattern supplies interchangeable implementations of an operation. This distinction concerns the pattern's principal responsibility; a system can use both kinds together.
The system uses the observer pattern with a pull-style update.
Equipment provides the subject interface and stores registered observers; GymEquipment is the concrete subject. Functionality is the observer interface, with Performance and Prediction as concrete observers. Their constructors subscribe them with addFunctionality(this).When
GymEquipment.updateUserMeasures is called, it first updates both measurements through super, then calls notifyFunctionalities. Every subscribed observer receives update() and reads the new measurements from its stored equipment reference. Performance calculates the current score; Prediction calculates the score at time time+5, keeping the other quantities fixed. Since observers are prepended to a list, notification follows reverse registration order.The source has two independent implementation defects.
deleteFunctionality(f) computes _functionalities diff List(f) but does not assign it back, so it does not actually unsubscribe anything. The prediction message also contains a physical newline inside an ordinary quoted Scala string in the PDF; executable code must join that string, concatenate pieces, or use a multiline string. Neither issue changes the intended observer pattern. The source's score is treated as the specified arithmetic expression, not as an independently validated physiological model.Introduce one shared
GymStandings singleton object. It stores the latest current-performance score for every participating GymEquipment, using the equipment reference as key, and returns every equipment object tied for the maximum score. Performance.update sends each freshly computed score to this object. The previous observer pattern and its prediction observer remain in use.The added
Performance -> GymStandings dependency means “reports to,” while GymStandings -> GymEquipment represents the equipment keys in its stored score map. GymStandings is an software object, so clients share its unique instance instead of constructing one standings object per machine. The singleton pattern centralizes the current scores and the maximum-score query. Equipment objects, rather than user names, are the keys because two users can have the same name. Scores are current readings, not an accumulation of all historical notifications; the largest reported score wins, with all ties retained.This is the Observer pattern, a behavioral pattern.
Service stores subscribers through the Company object interface. SomeService.updateValue first changes the underlying value and then sends a notification to every registered company; each company's meth() queries the new value and computes its own response. This is a pull-style notification: the message announces the change, while the observer reads the data from its retained subject reference.The UML class diagram shows the subject's collection of observers and the added concrete observer. Each concrete company also retains the
SomeService reference shown in its attributes; notifications call meth() through Company.Use an unscaled value both initially and in every callback:Initializing
class NonProfit(service: SomeService) extends Company {
private var v: Double = service.value
service.addCompany(this)
override def meth(): Unit = {
v = service.value
printf("New service value: %f\n", v)
}
}v before registration prevents a callback from observing an uninitialized field if registration is later extended to notify immediately. For a service initially valued at 100.0, this initializes v to 100.0; after updateValue(125.0), the callback sets v to 125.0 and prints New service value: 125.000000 under a decimal-point locale. The NonProfit update uses factor one.The word “always” requires a qualification in the supplied design. In the intended single-threaded notification protocol, holds after construction and after a completed
SomeService.updateValue. However, the printed public value_= setter changes the subject without calling sendMessage(). Calling service.value = ... can therefore leave every cached observer value stale. No implementation that merely caches v in meth() can guarantee literal equality after that unannounced change. If equality on every query is required, replace the field by private def v: Double = service.value, retaining registration and the same printing callback; alternatively every mutation route must notify observers. The source's distinct private/public company multipliers are not changed.The Observer pattern participants are:
Service: the subject abstraction, owning the current value and registeredCompanyreferences, and providing registration and notification operations.SomeService: the concrete subject, makingupdateValuenotify after establishing the new subject state.Company: the observer object interface, declaring themeth()callback.PrivateCompanyandPublicCompany, together with the extensionNonProfit: concrete observers, registering themselves, retaining their subject, and updating their own values on notification.
The printed
PrivateCompany starts with factor but uses factor in its callback; PublicCompany starts with factor but later uses . These are the actual source behaviors, not a uniform pricing rule inferred from their names. The subject stores a list and prepends new subscriptions, so notification occurs in reverse registration order. Dependence on the Company interface lets the subject notify new observer types without naming their concrete classes. The omitted ... portions in the printed figure do not prevent identifying these roles or implementing the added observer.The observer pattern is a behavioral design pattern defining a one-to-many dependency. When a subject changes relevant state, it notifies registered observers so they can update. The subject uses an observer interface rather than hard-coding each concrete dependent, allowing subscriptions to vary.
The observer pattern has four main roles. The subject maintains subscriptions and offers attach, detach and notification operations. The observer interface specifies an update callback. A concrete subject owns the relevant state and triggers notification when that state changes. A concrete observer implements the callback and updates its dependent state.
In a pull-style arrangement, a concrete observer retains a reference to the concrete subject and reads its state when notified; in a push-style arrangement, notification carries the changed information. Either way, the subject's notification loop calls observers through their interface. The roles should specify how subscription changes during notification are handled, for example by iterating a snapshot of the current observer list.
In the Observer pattern, an observable subject maintains subscriptions and sends notifications through a common observer interface when a relevant change occurs. Observers can then react to the event or query the subject's coherent new state. Registration and removal allow multiple dependants to change independently of the subject's application logic.
It is useful when one software object has several changing dependants, for example a document model with several views or a text field with an event handler. It avoids hard-coding every concrete dependant into the subject, reducing direct coupling and duplicated synchronization logic. Clients need not poll repeatedly to detect a change. This separation does not automatically prevent notification cycles, stale subscriptions, or inconsistent intermediate states: notification should occur after a coherent update, and observers should unregister when no longer needed. A reentrant event handler can otherwise commit recursively while refreshing a display.
A Scala Swing Here the containing frame supplies the reactor behavior, and each text field supplies publication. Defining
Publisher is the subject-side event source. Calling publish(e) notifies its subscribed reactors. A Reactor is the observer-side participant: listenTo(p1,p2) registers it with the specified sources, deafTo ends those subscriptions, and reactions contains the event-handling cases.listenTo(pounds, euros, rate)
reactions += {
case EditDone(source) => handleCommittedEdit(source)
}reactions without listenTo is insufficient to establish the subscription. The pattern-matching cases can handle only events of interest while other events are ignored. This is the Observer pattern expressed through event publication rather than a separate hand-written update method for every subject.[ref]Scala Swing event-system documentation. Archived Reactor API: listenTo, deafTo and reactions; official library README: Publisher/Reactor event-system overview
Model-view-controller divides an interactive application into a model containing application state and domain rules, a view rendering that state, and a controller interpreting user actions and requesting model operations. In the converter, the numeric amounts and exchange relation belong to the model, the text fields and labels form the view, and the edit handler parses input and chooses which quantity to preserve. A playlist model similarly owns song order independently of the controls used to change it.
A user acts through the view, the controller interprets that input, the model validates and commits a change, and the view then renders the resulting state. The exact packaging varies: a widget can combine view and controller responsibilities while still separating domain logic. Keeping the model independent of particular controls supports separation of concerns, encapsulation, reuse of the same model in several views, and unit testing of domain behavior without a graphical interface.
The Observer pattern often supplies the model-to-view notification path: views subscribe to model changes, so the model need not directly know every concrete view. It can also carry view input events to a controller, as in Scala Swing. Model-view-controller is an architectural separation of responsibilities; the Observer pattern is one mechanism for their communication. They are related without being identical, and small applications can implement the separation with direct calls where event subscriptions add no benefit.
The Observer pattern lets interested observers subscribe through a common interface to a subject's events or state changes. The subject notifies registered observers, which perform their own reactions; subscriptions can later be removed. A document model can thereby update multiple editor views without containing explicit knowledge of each view class.
It avoids tightly coupling the subject to every concrete consumer. Adding another view does not require adding a new view-specific call inside core model logic. Notifications should expose a coherent updated state, and unused observers should unsubscribe. The pattern does not itself prevent feedback cycles: observers that update each other's sources can still cause repeated or reentrant notifications. The supplied buttons and containing frame use this subscription-and-reaction design through Scala Swing.
In the Observer pattern, a subject maintains subscriptions through a common observation interface. Interested observers register and unregister; when a relevant state change occurs, the subject sends a notification, and each observer runs its own reaction. Notifications can carry the new information directly or prompt the observer to query the subject's coherent updated state.
This fits an event-driven programming interface in which one model can have several independently changing views: a displayed conversion, a chart or a status indicator can react to the same model change. It avoids hard-coding calls to every concrete view inside the subject, which would couple domain logic to presentation details and require editing the subject whenever another view is added. The subject depends on the observer interface rather than every concrete observer class.
The design still needs subscription cleanup and an update policy. Mutual notifications can create a feedback loop or a reentrant event handler, while an observer that reacts halfway through a state change can see inconsistent data. Publishing only coherent changes and controlling derived display updates address those problems; the pattern alone does not automatically solve them.
The observer pattern connects one event-producing subject to a changing set of interested consumers. Consumers register through an observation interface; when a relevant change occurs, the producer notifies them through that interface rather than naming every concrete consumer. Consumers can be added or removed without rewriting the producer's core behaviour.
This is useful for keeping displays, controls or other derived views synchronized with changing state. The design avoids tight coupling from the producer to all concrete dependants, which otherwise makes every new consumer require changes to the producer. Publishing after the producer's representation invariant has been restored also lets callbacks observe a coherent state. The pattern does not by itself prevent notification cycles or obsolete subscriptions; update policy and unregistration still matter.
Scala Swing Created 2026-10-24 Updated 2026-11-05
Scala Swing provides Scala wrappers for Java Swing graphical user interfaces. Its notification mechanism implements an observer pattern: a publisher emits software events, and a reactor subscribes with
listenTo(publisher). Adding a handler to reactions supplies a partial function that matches the software events the reactor handles. Subscription and handling are distinct: one determines which publisher is heard, and the other determines what to do with a matching notification.[ref]For example, a button publishes a button-click notification, and a subscribed display component handles it by updating a label. Another publisher's notifications need a subscription of their own. Calling
deafTo(publisher) ends the subscription to that publisher without requiring removal of every handler.[ref]
