抽象工厂

发表于:2007-07-04来源:作者:点击数: 标签:
为了给同事介绍抽象工厂写的小代码。 /************************** *抽象工厂模式 **************************/ #include iostream #include sstream #include string using namespace s td ; class Ram public: virtual void showSize()=0; ; class Cpu publ
为了给同事介绍抽象工厂写的小代码。

/**************************
 *抽象工厂模式
 **************************/

#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

原文转自:http://www.ltesting.net