2012/03/14

Observer pattern using template and Typelist

またまた Typelistの話題。これまでのTypelistの用法を参考にして、Design Patternのうち
有用な Observerパターンを考えてみましょう。

まずは Observerクラスから。これに関しては任意の型のイベントを受け取るといった想定
で、下記のようなシンプルなテンプレートクラスにします。


#ifndef OBSERVER_H_
#define OBSERVER_H_

#include "typelist.h"

template <typename T>
class Observer
{
public:
    virtual void update(const T& event) = 0;
    virtual ~Observer() {}
};

#endif // OBSERVER_H_

このObserverクラスに対する通知を担う Subjectクラスですが、ここでTypelistを使用
してみます。


#ifndef SUBJECT_H_
#define SUBJECT_H_

#include <vector>
#include "typelist.h"
#include "observer.h"

template <typename TL>
class Subject;

template <typename T, typename U>
class Subject< Typelist<T, U> > : public Subject<U>
{
    typedef std::vector<Observer<T>*> Vector;
public:
    Subject() : observers_()
    {
    }

    ~Subject()
    {
    }

    using Subject<U>::notify;
    void notify(const T& event)
    {
        typename Vector::iterator it = observers_.begin(), end_it = observers_.end();
        for (; it != end_it; ++it) {
            (*it)->update(event);
        }
    }

    using Subject<U>::attach;
    void attach(Observer<T>* observer_ptr)
    {
        observers_.push_back(observer_ptr);
    }

    using Subject<U>::detach;
    void detach(Observer<T>* observer_ptr)
    {
        typename Vector::iterator it = observers_.begin(), end_it = observers_.end();

        for (; it != end_it; ++it) {
            if ((*it) == observer_ptr) {
                break;
            }
        }

        if (it != end_it) {
            observers_.erase(it);
        }
    }

private:
    Vector observers_;
};

template <>
class Subject<NullType>
{
public:
    void notify(const NullType& /* no use */)
    {
    }

    void attach(const NullType& /* no use */)
    {
    }

    void detach(const NullType& /* no use */)
    {
    }
};

#endif // SUBJECT_H_

このSubjectクラスはテンプレートパラメータとしてTypelistを受け取り、Typelist要素の型
に対して attach, detach, notify操作を支援します。クライアントコードにおいては、
Subjectクラスオブジェクトをメンバーとして保有して、detach, attachを委譲するような
メソッドを定義してやれば良い感じになります。

EventTypeListという型でイベントの型集合のTypelistがあるとすると、attach, detachの
委譲メソッドは下記のような感じになります。

#ifndef CONCRETE_SUBJECT_H
#define CONCRETE_SUBJECT_H

#include "subject.h"
#include "event_type_list.h"

class ConcreteSubject
{
public:
    ConcreteSubject();

    template <typename T>
    void attach(Observer<T>* observer)
    {
        typedef typename TypelistOf<EventTypeList, T>::Result TL;
        subject_.Subject<TL>::attach(observer);
    }

    template <typename T>
    void detach(Observer<T>* observer)
    {
        typedef typename TypelistOf<EventTypeList, T>::Result TL;
        subject_.Subject<TL>::detach(observer);
    }

    void action1();
    void action2();

private:
    Subject<EventTypeList> subject_;
};

ここで TypelistOfは以前に紹介した Typelistの部分集合を取り出す操作になります。



Again, I would like to take a look at Typelist. Making use of what has been adopted
until now, I would like to come up with Observer pattern which is quite useful among
various Design Patterns.

First, let's take a look at Observer class. Since we would like to handle various event
types, we are supposed to make the Observer class as parameterized class
(template class) as follows.

#ifndef OBSERVER_H_
#define OBSERVER_H_

#include "typelist.h"

template <typename T>
class Observer
{
public:
    virtual void update(const T& event) = 0;
    virtual ~Observer() {}
};

#endif // OBSERVER_H_

Secondly, we are going to build up Subject class by making use of Typelist as
follows.

#ifndef SUBJECT_H_
#define SUBJECT_H_

#include <vector>
#include "typelist.h"
#include "observer.h"

template <typename TL>
class Subject;

template <typename T, typename U>
class Subject< Typelist<T, U> > : public Subject<U>
{
    typedef std::vector<Observer<T>*> Vector;
public:
    Subject() : observers_()
    {
    }

    ~Subject()
    {
    }

    using Subject<U>::notify;
    void notify(const T& event)
    {
        typename Vector::iterator it = observers_.begin(), end_it = observers_.end();
        for (; it != end_it; ++it) {
            (*it)->update(event);
        }
    }

    using Subject<U>::attach;
    void attach(Observer<T>* observer_ptr)
    {
        observers_.push_back(observer_ptr);
    }

    using Subject<U>::detach;
    void detach(Observer<T>* observer_ptr)
    {
        typename Vector::iterator it = observers_.begin(), end_it = observers_.end();

        for (; it != end_it; ++it) {
            if ((*it) == observer_ptr) {
                break;
            }
        }

        if (it != end_it) {
            observers_.erase(it);
        }
    }

private:
    Vector observers_;
};

template <>
class Subject<NullType>
{
public:
    void notify(const NullType& /* no use */)
    {
    }

    void attach(const NullType& /* no use */)
    {
    }

    void detach(const NullType& /* no use */)
    {
    }
};

#endif // SUBJECT_H_

This parameterized Subject class would intake Typelist as template parameter
and then support attach, detach and notify operations towards respective
Typelist element types. In client code, we are supposed to composite the Subject
class object and then write some appropriate attach and detach method as
delegation.

Assuming that EventTypeList is the Typelist for various event types we are going to
support here, delegation methods for attach and detach will be like the following.

#ifndef CONCRETE_SUBJECT_H
#define CONCRETE_SUBJECT_H

#include "subject.h"
#include "event_type_list.h"

class ConcreteSubject
{
public:
    ConcreteSubject();

    template <typename T>
    void attach(Observer<T>* observer)
    {
        typedef typename TypelistOf<EventTypeList, T>::Result TL;
        subject_.Subject<TL>::attach(observer);
    }

    template <typename T>
    void detach(Observer<T>* observer)
    {
        typedef typename TypelistOf<EventTypeList, T>::Result TL;
        subject_.Subject<TL>::detach(observer);
    }

    void action1();
    void action2();

private:
    Subject<EventTypeList> subject_;
};

Here, TypelistOf operation is what was introduced the other day.

2012/03/13

Biz trip to NY

業務上でしたが、先週初めてNew Yorkに行ってきました。

当然仕事なので、New York観光という訳にはなかなか行きませんでしたが、少しは観光する
ことが出来ました。

一つはスポーツや音楽のイベントの聖地とも言える「ザ・ガーデン」こと Madison Square
Gardenにてカレッジバスケットボールの観戦と、ブロードウェイ(正確にはオフ・ブロード
ウェイ)のミュージカルを見ることが出来ました。

カレッジバスケットボールでは Big East Conferenceと呼ばれるカンファレンスから
Louisville vs Setonhallと University of South Florida vs Villanova の試合を観戦。

個人的には 1試合目の Louisvilleの内容が良かった。効果的なゾーンディフェンスで相手の
切り込みを封じていたように見えたし、PGの選手のシュート、パスそれから身体能力の
高さに驚かされました。この選手、ちょっと調べてみたところそれなりに注目されている
選手のようで、下記のような記事もあったり、YouTube映像なども投稿されていました。
ぜひとも将来はNBA入りして頑張ってもらいたいですね。

Draft NBA Express - Peyton Siva

もう一つのブロードウェイは、英語があまり判らないだろうということで、台詞が理解でき
なくても楽しめそうなものとして Million Dollar Quartet というのを鑑賞しました。これは
1950年代のある日に収録されたジャムセッションを再現するような形で綴られた、古き良き
ロックンロールのミュージカルです。Surf, Garage, Rockabilly好きの私としては
たまらない内容でとても良かったです。

Official site - Million Dollar Quartet



I had a chance to travel to New York for the first time last week, although it was a biz
trip.

Although the purpose of the trip was, of course, business, I could have spent some
time for some sightseeing, visiting NYC.

Firstly, I visited so-called "The Garden" Madison Square Garden - holy place for
sports and music where I could watch college basketball. And also I watched a(n)
(Off-)Broadway musical.

In college basketball games, I watched the following 2 games from Big East
Conference - Louisville vs Setonhall and University of South Florida vs Villanova.

I enjoyed the first game (Louisville vs Setonhall) very much. Louisville's zone
defense seemed to me quite effective towards the opponent and then effectively
prevent them from penetrate into the inner area. And also the PG's was quite good
for shots, passes and his physical performance. According to google, it seems that
he is rather famous among basketball fans.


Draft NBA Express - Peyton Siva

I hope that he can turn pro - NBA in future and can even succeed in his career.

As for the musical in the broadway, since it was quite possible that I could not
understand the exact dialog in the play, I chose Million Dollar Quartet where I
expected that I could enjoy even if I could not understand the story. The motif
of this musical came from a certain famous rock & roll jam session in 1950s,
which should have definitely attracted me, since I'm a big fan of such kind of
music like Surf, Garage and Rockabilly etc..