LoginSignup
2
2

More than 5 years have passed since last update.

Node.js(ES6)でみるObserverパターン

Last updated at Posted at 2016-10-22

概念説明

以下の記事に任せます

ストーリー

ユーザーが会員登録した時点で

  • ユーザーに確認メールを送信
  • 管理者に通知メールを送信

を行いたい

デモ

コード

extendsされるSubjectクラス・Observerクラスの作成や、Value Objectの使用はサボってます。

// クラスの定義

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);

結果

console.log で出力されたもの

DBにユーザー情報を保存してPromiseを返す、ていで。
user.email宛に確認メールを送信する、ていで。
管理者のメールアドレス宛にuserの情報を含んだメールを送信する、ていで。
[ 'ユーザー確認メール送信完了', '管理者通知メール送信完了' ]
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2