// CplusplusAbstractFactory.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include<typeinfo> // "AbstractProductA" 草食动物 class Herbivore { }; // "AbstractProductB" 食肉动物 class Carnivore { public: // Methods virtual void Eat( Herbivore *h ) {}; }; // "ProductA1" class Wildebeest : public Herbivore { }; // "ProductA2" class Bison : public Herbivore { }; // "ProductB1" class Lion : public Carnivore { public: // Methods void Eat( Herbivore *h ) { // eat wildebeest printf("Lion eats %s\n",typeid(h).name()); } }; // "ProductB2" class Wolf : public Carnivore { public: // Methods void Eat( Herbivore *h ) { // Eat bison printf("Wolf eats %s\n",typeid(h).name()); } }; // "AbstractFactory" class ContinentFactory { public: // Methods virtual Herbivore* CreateHerbivore() { return new Herbivore(); } virtual Carnivore* CreateCarnivore() { return new Carnivore(); } }; // "ConcreteFactory1" class AfricaFactory : public ContinentFactory { public: // Methods Herbivore* CreateHerbivore() { return new Wildebeest(); } Carnivore* CreateCarnivore() { return new Lion(); } }; // "ConcreteFactory2" class AmericaFactory : public ContinentFactory { public: // Methods Herbivore* CreateHerbivore() { return new Bison(); } Carnivore* CreateCarnivore() { return new Wolf(); } }; // "Client" class AnimalWorld { private: // Fields Herbivore* herbivore; Carnivore* carnivore; public: // Constructors AnimalWorld( ContinentFactory *factory ) { carnivore = factory->CreateCarnivore(); herbivore = factory->CreateHerbivore(); } // Methods void RunFoodChain() { carnivore->Eat(herbivore); } }; int _tmain(int argc, _TCHAR* argv[]) { // Create and run the Africa animal world ContinentFactory *africa = new AfricaFactory(); AnimalWorld *world = new AnimalWorld( africa ); world->RunFoodChain(); // Create and run the America animal world ContinentFactory *america = new AmericaFactory(); world = new AnimalWorld( america ); world->RunFoodChain(); return 0; }
在以下情况下应当考虑使用抽象工厂模式: