设计模式-工厂模式

今天学习了C++设计模式的工厂模式,提供的示例代码比较简单,但足以说明工厂模式是怎么实现的。

工厂模式的两个特点:

        1、工厂模式封装了创造对象的接口

        2、将对象的创建延迟到子类,具体的实例化由子类提供。


示例代码如下:

//product.h

#ifndef _PRODUCT_H
#define _PRODUCT_H


class Product
{
public:
virtual ~Product() = 0;


protected:
Product();


};


class ConcreteProduct :public Product
{
public:
ConcreteProduct();
~ConcreteProduct();
};


#endif


//product.c

#include "factory.h"
#include "product.h"


#include <iostream>


using namespace std;


Factory::Factory()
{


}


Factory::~Factory()
{


}


ConcreteFactory::ConcreteFactory()
{
cout<<"this is ConcreteFactory"<<endl;
}


ConcreteFactory::~ConcreteFactory()
{


}


Product* ConcreteFactory::CreateProduct()
{
return new ConcreteProduct();
}


//factory.h

#ifndef _FACTORY_H
#define _FACTORY_H


class Product;


class Factory
{
public:
virtual ~Factory() =0;
virtual Product* CreateProduct()=0;


protected:
Factory();
};


class ConcreteFactory: public Factory
{
public:
ConcreteFactory();
~ConcreteFactory();
Product* CreateProduct();
};


#endif


//factory.c

#include "factory.h"
#include "product.h"


#include <iostream>


using namespace std;


Factory::Factory()
{


}


Factory::~Factory()
{


}


ConcreteFactory::ConcreteFactory()
{
cout<<"this is ConcreteFactory"<<endl;
}


ConcreteFactory::~ConcreteFactory()
{


}


Product* ConcreteFactory::CreateProduct()
{
return new ConcreteProduct();
}


在这里为子类ConcreteProduct实现了自己的ConcreteFactory工厂,如果有更多的子类,可以为具体的子类实现自己的创建对象工厂,也可以在原有工厂类的基础上,让创建对象接口参数化,根据具体的参数,创建对应的对象。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值