/**************************
*抽象工廠模式
**************************/
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
class Ram{
public:
virtual void showSize()=0;
};
class Cpu{
public:
virtual void showHz()=0;
};
class Factory{
public:
virtual Ram *createRam()=0;
virtual Cpu *createCpu()=0;
};
class pcRam:public Ram{
public:
void showSize(){
cout << "this Pc Ram size show"<<endl;
}
};
class macRam:public Ram{
public:
void showSize(){
cout << "this mac Ram size show"<<endl;
}
};
class pcCpu:public Cpu{
public:
void showHz(){
cout << "this pc cpu hz show"<<endl;
}
};
class macCpu:public Cpu{
public:
void showHz(){
cout << "this mac cpu hz show"<<endl;
}
};
class pcFactory:public Factory{
public:
Ram *createRam(){
cout << "this pc ram..."<<endl;
return new pcRam();
}
Cpu *createCpu(){
cout << "this pc cpu..."<<endl;
return new pcCpu();
}
};
class macFactory:public Factory{
public:
Ram *createRam(){
cout << "this mac ram..."<<endl;
return new macRam();
}
Cpu *createCpu(){
cout << "this mac cpu..."<<endl;
return new macCpu();
}
};
class Computer{
public:
Computer *createComputer(Factory &factory)
{
Ram *ram=factory.createRam();
Cpu *cpu=factory.createCpu();
ram->showSize();
cpu->showHz();
return this;
}
};
int main()
{
Factory *pcfy=new pcFactory();
Factory *macfy=new macFactory();
Computer pc;
pc.createComputer(*macfy);
exit(0);
}
運行結果:
[root@stone pattern]# ./afactory
this mac ram...
this mac cpu...
this mac Ram size show
this mac cpu hz show