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

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


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值