Design&Art

C++博客 首页 新随笔 联系 聚合 管理
  26 Posts :: 0 Stories :: 38 Comments :: 0 Trackbacks

工厂方法和抽象工厂实际上是从不同角度在描述问题。
工厂方法描述了具体产品的创建,而抽象工厂描述的是产品系列的组织。

//  Computer.cpp : Defines the entry point for the console application.
//

#include 
" stdafx.h "
#include 
< string >
#include 
< iostream >

using   namespace  std;

class  Ram {} ;
class  IBMRam:  public  Ram {} ;
class  HPRam:  public  Ram {} ;
class  Cpu {} ;
class  IBMCpu:  public  Cpu {} ;
class  HPCpu:  public  Cpu {} ;

class  Computer
{
public :
 Computer(
string  strName, Ram *  pRam, Cpu *  pCpu)
 
{
  m_strName 
=  strName;
  m_pRam 
=  pRam;
  m_pCpu 
=  pCpu;
  cout
<< " " <<  m_strName  << "  computer is produced " << endl;
 }

 
~ Computer()
 
{
  delete m_pRam;
  delete m_pCpu;
  cout
<< " " <<  m_strName  << "  computer is deleted " << endl;
 }

public :
 
string  m_strName;
private :
 Ram
*  m_pRam;
 Cpu
*  m_pCpu;
}
;

class  ComputerProducer
{
public :
 Computer
*  createComputer()
 
{
  
return   new  Computer(setName(), createRam(), createCpu());
 }

 
virtual  Ram *  createRam()  =   0 ;
 
virtual  Cpu *  createCpu()  =   0 ;
 
virtual   string  setName()  =   0 ;
}
;

class  IBMProducer:  public  ComputerProducer
{
public :
 
virtual  Ram *  createRam()
 
{
  cout
<< " A IBMRam is producted " << endl;
  
return   new  IBMRam;
 }

 
virtual  Cpu *  createCpu()
 
{
  cout
<< " A IBMCPU is producted " << endl;
  
return   new  IBMCpu;
 }

 
virtual   string  setName()
 
{
  
return   string ( " IBM " );
 }

}
;

class  HPProducer:  public  ComputerProducer
{
public :
 
virtual  Ram *  createRam()
 
{
  cout
<< " A HPRam is producted " << endl;
  
return   new  HPRam;
 }

 
virtual  Cpu *  createCpu()
 
{
  cout
<< " A HPCPU is producted " << endl;
  
return   new  HPCpu;
 }

 
virtual   string  setName()
 
{
  
return   string ( " HP " );
 }

}
;

int  main( int  argc,  char *  argv[])
{
 
//  client code
 ComputerProducer *  pIBMFac =   new  IBMProducer;
 ComputerProducer
*  pHPFac  =   new  HPProducer;
 Computer
*  pIBMComputer  =  pIBMFac -> createComputer();
 Computer
*  pHPComputer  =  pHPFac  -> createComputer();
 delete pIBMComputer;
 delete pHPComputer;
 delete pIBMFac;
 delete pHPFac;
 
return   0 ;
}


这个例子比较清楚了,不同的工厂生产不同的计算机,但计算机的基本组成(这里假设计算机仅由ram和cpu组成)是一样的,这样的产品系列很适合用抽象工厂来组织。
而在实际生产计算机的时候,createRam()和createCpu()这两个工厂方法又起到了作用。

posted on 2007-03-25 23:20 安帛伟 阅读(1082) 评论(0)  编辑 收藏 引用 所属分类: 设计模式

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理