~cpp
class Creator {
public:
virtual Product* Create(ProductId);
};
Product* Creator::Create (ProductId id) {
if (id == MINE) return new MyProduct;
if (id == YOURS) return new YourProduct;
// 남은 product의 종류의 반복
return 0;
}
~cpp
Product* MyCreator::Create (ProductId id) {
if (id == YOURS) return new MyProduct;
if (id == MINE) return new YourProduct;
// YouProduct와 MyProduct 교환
if (id == THEIRS) return new TheirProduct; // 새로운 product 추가
return Creator::Create(id); // 만약 모두가 실패하면 기본 생성자를 부른다.
}
DeleteMe 모호)마지막 부분에서 부모 클래스의 인자를 수행하는 것을 주목해라. MyCreator::Create는 오직 YOURS, MINE, THEIRS를 잡을수 있고, 부모클래스는 잡지 못한다. 다른 클래스는 이를 수행하지 못한다. 그러므로, MyCreator는 생성된 product의 한 종류를 확장하고, 그것은 생성에 대한 책임을 연기한다. 하지만, product가 그것의 부모인것은 적다.~cpp
clientMethod
document := self documentClass new.
documentClass
self subclassResponsibility
~cpp
documentClass
^ MyDocument
~cpp
class Creator {
public:
Product* GetProduct();
protected:
virtual Product* CreateProduct();
private:
Product* _product;
};
Product* Creator::GetProduct () {
if (_product == 0) {
_product = CreateProduct();
}
return _product;
}
~cpp
class:
class Creator {
public:
virtual Product* CreateProduct() = 0;
};
template
class StandardCreator: public Creator {
public:
virtual Product* CreateProduct();
};
template
Product* StandardCreator::CreateProduct () {
return new TheProduct;
}
~cpp
class MyProduct : public Product {
public:
MyProduct();
// ...
};
StandardCreator myCreator;
~cpp
class MazeGame {
public:
Maze* CreateMaze();
// factory methods:
virtual Maze* MakeMaze() const
{ return new Maze; }
virtual Room* MakeRoom(int n) const
{ return new Room(n); }
virtual Wall* MakeWall() const
{ return new Wall; }
virtual Door* MakeDoor(Room* r1, Room* r2) const
{ return new Door(r1, r2); }
};
~cpp
Maze* MazeGame::CreateMaze () {
Maze* aMaze = MakeMaze();
Room* r1 = MakeRoom(1);
Room* r2 = MakeRoom(2);
Door* theDoor = MakeDoor(r1, r2);
aMaze->AddRoom(r1);
aMaze->AddRoom(r2);
r1->SetSide(North, MakeWall());
r1->SetSide(East, theDoor);
r1->SetSide(South, MakeWall());
r1->SetSide(West, MakeWall());
r2->SetSide(North, MakeWall());
r2->SetSide(East, MakeWall());
r2->SetSide(South, MakeWall());
r2->SetSide(West, theDoor);
return aMaze;
}
~cpp
class BombedMazeGame : public MazeGame {
public:
BombedMazeGame();
virtual Wall* MakeWall() const
{ return new BombedWall; }
virtual Room* MakeRoom(int n) const
{ return new RoomWithABomb(n); }
};
~cpp
class EnchantedMazeGame : public MazeGame {
public:
EnchantedMazeGame();
virtual Room* MakeRoom(int n) const
{ return new EnchantedRoom(n, CastSpell()); }
virtual Door* MakeDoor(Room* r1, Room* r2) const
{ return new DoorNeedingSpell(r1, r2); }
protected:
Spell* CastSpell() const;
};