Last active
October 22, 2016 07:59
-
-
Save YutaroSoejima/9fb5afe3beb37be6e3f348f2f62d659a to your computer and use it in GitHub Desktop.
Node.js(ES6)でみるObserverパターン ref: http://qiita.com/yutarosoejima/items/a8caa505225e137b34ca
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// クラスの定義 | |
class User { | |
constructor(name, email) { | |
this.name = name; | |
this.email = email; | |
} | |
save() { | |
console.log('DBにユーザー情報を保存してPromiseを返す、ていで。'); | |
return new Promise(resolve => resolve(this)); | |
} | |
} | |
class UserRegistrationSubject { | |
constructor() { | |
this.observers = []; | |
} | |
registerObserver(observer) { | |
this.observers.push(observer); | |
} | |
notifyObservers(user) { | |
return Promise.all(this.observers.map(o => o.getNotified(user))); | |
} | |
} | |
class UserConfirmationObserver { | |
constructor(subject) { | |
subject.registerObserver(this); | |
} | |
getNotified(user) { | |
console.log('user.email宛に確認メールを送信する、ていで。'); | |
return new Promise(resolve => resolve('ユーザー確認メール送信完了')); | |
} | |
} | |
class AdministratorNotificationObserver { | |
constructor(subject) { | |
subject.registerObserver(this); | |
} | |
getNotified(user) { | |
console.log('管理者のメールアドレス宛にuserの情報を含んだメールを送信する、ていで。'); | |
return new Promise(resolve => resolve('管理者通知メール送信完了')); | |
} | |
} | |
// Observerパターンのデモ | |
const subject = new UserRegistrationSubject(); | |
const UCObserver = new UserConfirmationObserver(subject); | |
const ANObserver = new AdministratorNotificationObserver(subject); | |
const user = new User('山田太郎', 'hoge@example.com'); | |
user.save() | |
.then(user => subject.notifyObservers(user)) | |
.then(console.log); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DBにユーザー情報を保存してPromiseを返す、ていで。 | |
user.email宛に確認メールを送信する、ていで。 | |
管理者のメールアドレス宛にuserの情報を含んだメールを送信する、ていで。 | |
[ 'ユーザー確認メール送信完了', '管理者通知メール送信完了' ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment