MVC divides an application into three parts, the model, view, and controller.
Models use the Observer pattern to notify views that data has changed.
Views use the Composite pattern to create a hierarchy of UI elements.
Controllers use the Strategy pattern to handle events from views.
Views are always hierarchies, with one single “top view”, and many child views.
A single view can represent both single items, such as a checkbox, or more
complex components, such as a list of selectable items.
The top view and other views which can have children, implement the
ViewComposite class, which is the Composite in the Composite pattern.
Views that do not have children implement the ViewLeaf class, which is the
Leaf in the Composite pattern. Both classes inherit from ViewComponent
(Component), which in turn inherits from ViewObserver (Observer).
Views and controllers are tightly coupled. They both maintain a reference to the
other. We minimize this coupling by forcing views to communicate with
their respective controllers through the ControllerContext class, which is the
Context part of the Strategy pattern and can be viewed as a sort of
Facade. This communication happens transparently.
Lastly, models can be strings, a single object, or a collection of objects as
long as they inherit from ModelSubject.
classDiagram
class Model{
<<Subject>>
attach(observer)
detatch(observer)
notify()
}
class View{
<<Observer>>
update()
}
class TodoModel{
<<ConcreteSubjectA>>
-string title
getTitle()
setTitle(title)
}
class TodosModel{
<<ConcreteSubjectB>>
-string todos
getTodos()
addTodo(todo)
}
class Component{
<<ConcreteObserver>>
display()
add(name, component)
remove(name)
update(model)
}
note for Component "Strategy+Composite"
class AppController{
<<ConcreteStrategy>>
onAdd(data)
onChoice(choice)
}
class TopView {
<<Composite>>
}
class AddView {
<<Leaf>>
}
class ListView {
<<Leaf>>
}
class ChoiceView {
<<Leaf>>
}
class Controller {
<<Strategy>>
}
class Context
Controller <|-- AppController
Controller <--o Context : strategy
Component <--o AppController : context
Component <|-- AddView
Component <|-- ListView
Component <|-- ChoiceView
Component <--o TopView
Component <|-- TopView
TodosModel <-- Component : subject
TodoModel <-- Component : subject
Model <|-- TodoModel
Model <|-- TodosModel
View <|-- Component
View <--o Model : observers
Resources
Authoritative documentation on the Smalltalk approach to MVC is hard to find.
These resources are excellent if you want a straight-from-the-source explanation.