
今度は、プラダの鞄でも最初の製品だけを好む、という設定にしてみます。同じオブジェクトでも最初だけっていうのは製造番号が付いているとか、シルクスクリーンに番号が振ってあるとか、限定品っていう意味合いですね。これは、COM で言うところの参照カウンタと同じです。
// for アリスは初物がお好き
#include <iostream>
using namespace std;
class Bag {
protected:
bool used;
static int _count;
public:
Bag() : used(false) {
_count++;
cout << "constractor " << _count << endl;
}
bool getUsed() { return used; }
void Used() { this->used = true; }
// 参照カウンタ
int getCount() { return _count; }
};
// 参照カウンタを初期化
int Bag::_count = 0;
class Prada : public Bag {};
class Tiffany : public Bag {};
// 初物好きなアリス
class Alice
{
public:
Alice() {}
bool DoYouLike( Bag *bag )
{
if ( bag->getCount() != 1 || bag->getUsed() == true ) {
return false;
} else {
return true;
}
}
void Use( Bag *bag ) {
bag->Used();
}
};
// 悪友ロリータ
class Lolita
{
public:
bool DoYouLike( Bag *bag ) {
return true;
}
void Use( Bag *bag ) {
bag->Used();
}
};
int main(void)
{
Alice alice;
Lolita lolita;
{
Prada bag;
if ( alice.DoYouLike( &bag ) ) {
cout << "alice like first Prada." << endl;
} else {
cout << "alice don't like other Prada." << endl;
}
}
{
Prada bag;
// アリスは初物じゃなくちゃ嫌
if ( alice.DoYouLike( &bag ) ) {
cout << "alice like first Prada." << endl;
} else {
cout << "alice don't like other Prada." << endl;
}
}
return 0;
}
同じように Prada bag として bag を作成しているけど、最初の bag と次の bag は違います。C++ の場合は参照カウンタをクラスの外で初期化しないと駄目なんですが(C++0x だとできたっけ?)、C# だとクラス内で初期化ができるので static で指定すればOK。
using System;
public class Bag {
protected bool _used = false;
protected static int _count = 0;
public Bag() {
_count++;
}
public void Use() {
_used = true;
}
public bool Used {
get { return _used; }
}
public int Count {
get { return _count; }
}
}
public class Prada : Bag {}
public class Tiffany : Bag {}
// 初物好きなアリス
public class Alice {
public bool DoYouLike( Bag bag ) {
if ( bag.Count != 1 || bag.Used == true ) {
return false;
} else {
return true;
}
}
}
public class Program {
public static void Main(string []args ) {
Alice alice = new Alice();
Prada prada = new Prada();
if ( alice.DoYouLike( prada ) ) {
Console.WriteLine("alice likes first prada.");
} else {
Console.WriteLine("alice don't like other prada.");
}
// 2つ目を作る
prada = new Prada();
if ( alice.DoYouLike( prada ) ) {
Console.WriteLine("alice likes first prada.");
} else {
Console.WriteLine("alice don't like other prada.");
}
}
}
