工厂方法和抽象工厂

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

//  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()这两个工厂方法又起到了作用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值