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

1、意图

    Provide an interface for creating families of related or dependent objects without specifying their concrete classes. 

 

2、适应性

Use the Abstract Factory pattern when     ••

    •  a system should be independent of how its products are created, composed, and represented.

    •  a system should be configured with one of multiple families of products.

    •  a family of related product objects is designed to be used together, and you need to enforce this constraint.

    • you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.

 

3、结构

                  

 

4、示例代码 

class MazeFactory { 
    public: 
        MazeFactory(); 
     
        virtual Maze* MakeMaze() const 
            { return new Maze; } 
        virtual Wall* MakeWall() const 
            { return new Wall; } 
        virtual Room* MakeRoom(int n) const 
            { return new Room(n); } 
        virtual Door* MakeDoor(Room* r1, Room* r2) const 
            { return new Door(r1, r2); } 
    }; 

 class EnchantedMazeFactory : public MazeFactory { 
    public: 
        EnchantedMazeFactory(); 
     
        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; 
    }; 

 
   Maze* MazeGame::CreateMaze (MazeFactory& factory) { 
        Maze* aMaze = factory.MakeMaze(); 
        Room* r1 = factory.MakeRoom(1); 
        Room* r2 = factory.MakeRoom(2); 
        Door* aDoor = factory.MakeDoor(r1, r2); 
     
        aMaze->AddRoom(r1); 
        aMaze->AddRoom(r2); 
     
        r1->SetSide(North, factory.MakeWall()); 
        r1->SetSide(East, aDoor); 
        r1->SetSide(South, factory.MakeWall()); 
        r1->SetSide(West, factory.MakeWall()); 
     
        r2->SetSide(North, factory.MakeWall()); 
        r2->SetSide(East, factory.MakeWall()); 
        r2->SetSide(South, factory.MakeWall()); 
        r2->SetSide(West, aDoor); 
     
        return aMaze; 
    } 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值