编程语言
首页 > 编程语言> > 工厂方法C++示例

工厂方法C++示例

作者:互联网

工厂方法UML图


//AbstractFactory.h
#ifndef ABSTRACTFACTORY_H
#define ABSTRACTFACTORY_H


class AbstractProduct;
class AbstractFactory
{
public:
   virtual AbstractProduct* createProduct()=0;

};



#endif


//AbstractProduct.h
#ifndef ABSTRACTPRODUCT_H
#define ABSTRACTPRODUCT_H

class AbstractProduct
{
public:
    virtual void color()=0;
    virtual void shape()=0;
};

#endif




//FactoryA.h

#ifndef FACTORYA_H
#define FACTORYA_H

#include "AbstractFactory.h"
class AbstractProduct;
class FactoryA:public AbstractFactory
{
public:
  virtual AbstractProduct* createProduct();

};



#endif


//FactoryA.cpp

#include "FactoryA.h"
#include "ProductA.h"


AbstractProduct *FactoryA::createProduct()
{
    return new ProductA();
}


//FactoryB.h

#ifndef FACTORYB_H
#define FACTORYB_H

#include "AbstractFactory.h"
class AbstractProduct;
class FactoryB:public AbstractFactory
{
public:
  virtual AbstractProduct* createProduct();

};



#endif


//FactoryB.cpp

#include <QString>
#include "FactoryB.h"
#include "ProductB.h"


AbstractProduct *FactoryB::createProduct()
{
    return new ProductB();
}



//ProductB.h

#ifndef PRODUCTB_H
#define PRODUCTB_H

#include "AbstractProduct.h"

class ProductB:public AbstractProduct
{
public:
    ProductB();
    virtual void color();
    virtual void shape();

};


#endif

//ProductB.cpp

#include <QDebug>
#include "ProductB.h"

ProductB::ProductB()
{

}

void ProductB::color()
{
    qDebug("The ProductB is black");
}
void ProductB::shape()
{
   qDebug("The ProductB is triangle");
}

 

标签:ProductB,示例,class,C++,工厂,AbstractProduct,virtual,include,public
来源: https://blog.csdn.net/weixin_40767138/article/details/89683230