举例解析设计模式中的工厂方法模式在C++编程中的运用

2020-01-06 14:41:18王旭
易采站长站为您分析设计模式中的工厂方法模式在C++编程中的运用,文中也对简单工厂模式和工厂方法模式进行了简单的对比,需要的朋友可以参考下  

工厂方法模式不同于简单工厂模式的地方在于工厂方法模式把对象的创建过程放到里子类里。这样工厂父对象和产品父对象一样,可以是抽象类或者接口,只定义相应的规范或操作,不涉及具体的创建或实现细节。
其类图如下:

举例解析设计模式中的工厂方法模式在C++编程中的运用

实例代码为:


#pragma once 
class IProduct 
{ 
public: 
  IProduct(void); 
  virtual ~IProduct(void); 
}; 
 
#pragma once 
#include "iproduct.h" 
class IPad : 
  public IProduct 
{ 
public: 
  IPad(void); 
  ~IPad(void); 
}; 
 
#pragma once 
#include "iproduct.h" 
class IPhone : 
  public IProduct 
{ 
public: 
  IPhone(void); 
  ~IPhone(void); 
}; 


#pragma once 
#include"IProduct.h" 
 
class IFactory 
{ 
public: 
  IFactory(void); 
  virtual ~IFactory(void); 
 
  virtual IProduct* getProduct(); 
}; 
 
 
#pragma once 
#include "ifactory.h" 
class IPadFactory : 
  public IFactory 
{ 
public: 
  IPadFactory(void); 
  ~IPadFactory(void); 
 
  virtual IProduct* getProduct(); 
}; 
 
 
#pragma once 
#include "ifactory.h" 
class IPhoneFactory : 
  public IFactory 
{ 
public: 
  IPhoneFactory(void); 
  ~IPhoneFactory(void); 
 
  virtual IProduct* getProduct(); 
}; 

关键的实现:


#include "StdAfx.h" 
#include "IPadFactory.h" 
#include"IPad.h" 
 
IPadFactory::IPadFactory(void) 
{ 
} 
 
 
IPadFactory::~IPadFactory(void) 
{ 
} 
 
IProduct* IPadFactory::getProduct() 
{ 
  return new IPad(); 
} 
 
 
#include "StdAfx.h" 
#include "IPhoneFactory.h" 
#include"IPhone.h" 
 
IPhoneFactory::IPhoneFactory(void) 
{ 
} 
 
 
IPhoneFactory::~IPhoneFactory(void) 
{ 
} 
 
 
IProduct* IPhoneFactory::getProduct() 
{ 
  return new IPhone(); 
} 

调用方式:


#include "stdafx.h" 
#include"IFactory.h" 
#include"IPadFactory.h" 
#include"IPhoneFactory.h" 
#include"IProduct.h" 
 
 
int _tmain(int argc, _TCHAR* argv[]) 
{ 
  IFactory *fac = new IPadFactory(); 
  IProduct *pro = fac->getProduct(); 
 
  fac = new IPhoneFactory(); 
  pro = fac->getProduct(); 
  return 0; 
}