前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >工厂方法模式

工厂方法模式

作者头像
用户1215536
发布2018-02-05 11:04:41
3730
发布2018-02-05 11:04:41
举报

一、相关介绍

1、工厂方法模式定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。

2、UML图

3、所属类别:创建型

二、C++代码

代码语言:javascript
复制
// 工厂方法模式.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
using namespace std;
//抽象产品
class fruit
{
public:
	fruit();
	virtual ~fruit();
	//由于此类是抽象类,没有价格,所以只能将价格显示定义为纯虚函数
	virtual void show_price()=0;
};
fruit::fruit()
{}
fruit::~fruit()
{}

//具体产品1
class apple :public fruit
{
public :
	apple();
	virtual ~apple();
	virtual void show_price();
};
apple::apple()
{
	cout<<"i am an apple"<<endl;
}
apple::~apple()
{}
void apple::show_price()
{
	cout<<"my price is 5"<<endl;
}

//具体产品2
class orange :public fruit
{
public :
	orange();
	virtual ~orange();
	virtual void show_price();
};
orange::orange()
{
	cout<<"i am an orange"<<endl;
}
orange::~orange()
{}
void orange::show_price()
{
	cout<<"my price is 6"<<endl;
}
//工厂抽象类
//输入要创建实例的编号,创建对应实例,1:apple,2:orange
class fruit_factory
{
public:
	fruit_factory(){}
	~fruit_factory(){}
	virtual fruit *creat_fruit()=0;
};
//apple工厂类
class apple_factory:public fruit_factory
{
public:
	apple_factory(){}
	~apple_factory(){}
	virtual fruit * creat_fruit()
	{
	    return new apple;
	}
};

//orange工厂类
class orange_factory:public fruit_factory
{
public:
	orange_factory(){}
	~orange_factory(){}
	virtual fruit * creat_fruit()
	{
	    return new orange;
	}
};
int _tmain(int argc, _TCHAR* argv[])
{
	orange_factory chengzi_f;
	fruit *chengzi;
	chengzi=chengzi_f.creat_fruit();
	(*chengzi).show_price();
	return 0;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-01-16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档