function main() { var c = new Controller(); c.next(); // 1 c.next(); // 2 c.prev(); // 1 } class Model { constructor() { this.num = 0; } addEventListener(listener) { this.listener = listener; } next() { this.num++; this.listener.refresh(); } prev() { this.num--; this.listener.refresh(); } } class View { constructor(model) { this.model = model; } refresh() { console.log(this.model.num); } } class Controller { constructor() { this.model = new Model(); this.view = new View(this.model); this.model.addEventListener(this.view); } next() { this.model.next(); } prev() { this.model.prev(); } }
ModelはControllerやViewに依存しない。viewを更新するためのインターフェースに依存する。
ViewはModelに依存してもよい。
Controllerの内部に関しては、直接実装に依存してよいし、グローバル変数的なメンバ変数を持っていい。複雑な動きはModelに押し込む。