《《设计模式02》-工厂方法》由会员分享,可在线阅读,更多相关《《设计模式02》-工厂方法(24页珍藏版)》请在金锄头文库上搜索。
1、第二部分 创建型设计模式v工厂方法模式(Factory Method Pattern)v简单工厂模式(Simple Factory Pattern)v单件模式(Singleton Pattern)v构造器模式(Builder Pattern)v原型模式(Prototype Pattern)v抽象工厂模式(Abstract Factory Pattern)工厂方法模式CreateAndUse()class Clientpublic:void CreateAndUse() int sum = 0;Dog * dog = new Dog;sum+= dog-Sale();delete dog;Cat
2、 * cat = new Cat;sum+= cat-Sale();delete cat;Fish * fish = new Fish;sum+= fish-Sale();delete fish;coutsumSale(); delete ani ; IAnimal * ani = new Cat;sum+= cat-Sale();delete ani ; IAnimal * ani = new Fish;sum+= ani Sale();delete ani ;coutsumSale();delete ani;IAnimal * ani = CreateCat();sum+= ani-Sal
3、e();delete ani;IAnimal * ani = CreateFish();sum+= ani-Sale();delete ani;cout“Total Sale:”Sale();delete ani;IAnimal * ani = fac. CreateCat();sum+= ani-Sale();delete ani;IAnimal * ani = fac. CreateFish();sum+= ani-Sale();delete ani;cout“Total Sale:”Sale();delete ani;IAnimal * ani = fac. CreateAnimal(C
4、);sum+= ani-Sale();delete ani;IAnimal * ani = fac. CreateAnimal(F);sum+= ani-Sale();delete ani;cout“Total Sale:”AddRoom(r1); aMaze-AddRoom(r2); r1-SetSide(North,makeWall(); r1-SetSide(East,door); r1-SetSide(South,makeWall(); r1-SetSide(West,makeWall(); r2-SetSide(North,makeWall(); r2-SetSide(East, m
5、akeWall(); r2-SetSide(South,makeWall(); r2-SetSide(West,door); return aMaze; MazeFactory的子类BombedMazeFactoryclass BombedMazeFactory:public MazeFactor Public: BombedMazeFactory(); virtual Wall * MakeWall() const return new BombedWall; virtual Room * MakeRoom(int n) const return new RoomWithABomb(n);
6、;MazeFactory的子类EnchantedMazeFactoryclass EnchantedMazeFactory:public MazeFactroy 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 * CastS
7、pell() const;Factory的使用Class GamePublic: Game(MazeFactory & fac ) aMaze = fac.CreateMaze(); Private: Maze * aMaze;Factory中的CreateMaze也可以放到Game中。Class GamePublic: Game(MazeFactory & fac ) aMaze = CreateMaze(fac); Protected: Maze * CreateMaze(MazeFactory & fac ) /将例中的MakeRoom等改成 /fac.MakeRoom。略Private: Maze * aMaze;vtemplate vclass MyCreator:public Creatorvvpublic: v virtual Product * CreateProduct();v;vtemplate vProduct * MyCreator:CreateProduct( )v v return new TheProduct;v