笔记:Gof设计模式--Factory Method

来源:互联网 发布:如何打开软件蜂窝数据 编辑:程序博客网 时间:2024/06/07 23:08

1、意图

    Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

 

2、适应性

Use the Factory Method pattern when
    •  a class can't anticipate the class of objects it must create.
    •  a class wants its subclasses to specify the objects it creates.
    •  classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.

 

3、结构

 

4、示例代码

   First we'll define factory methods in MazeGame for creating the maze, room, wall, and door objects:

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


    MazeGame subclasses can redefine some or all of the factory methods to specify variations in products. For example, a BombedMazeGame can redefine the Room and Wall products to return the bombed varieties:

  class BombedMazeGame : public MazeGame {     public:         BombedMazeGame();              virtual Wall* MakeWall() const             { return new BombedWall; }              virtual Room* MakeRoom(int n) const             { return new RoomWithABomb(n); }     };

 

    An EnchantedMazeGame variant might be defined like this:

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


    Now we can rewrite CreateMaze to use these factory methods:

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


 

原创粉丝点击