歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Unix知識 >> 關於Unix

抽象工廠

為了給同事介紹抽象工廠寫的小代碼。 /************************** *抽象工廠模式 **************************/ #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

Copyright © Linux教程網 All Rights Reserved