首页 > 代码库 > 设计模式C++实现_2_简单工厂模式

设计模式C++实现_2_简单工厂模式

简单工厂模式


主要用于创建对象。 新加入类时。 不会影响曾经的系统代码。

核心思想是用一个工厂来依据输入的条件产生不同的类,然后依据不同类的 virtual 函数得到不同的结果.


以下以苹果手机的生产为例。模拟手机生产工厂。

苹果手机有各种不同的型号,有Iphone4、Iphone4s、Iphone5等等。

我们通过一个工厂来生产,client依据客户的需求生产不同型号的手机。

代码例如以下:

Apple.h

#pragma once
#include <iostream>

class Apple
{
public:
	Apple();
	virtual ~Apple();

	virtual void ShowVersion() = 0;
	virtual void MakeCall(const std::string &num) = 0;
};

Apple.cpp

#include "Apple.h"

Apple::Apple()
{
}

Apple::~Apple()
{
}

Apple4.h

#pragma once
#include "Apple.h"

class Apple4 : public Apple
{
public:
	Apple4();
	~Apple4();

	virtual void ShowVersion();
	virtual void MakeCall(const std::string &num);
};

Apple4.cpp

#include "Apple4.h"
#include <iostream>
#include <string>

using namespace std;

Apple4::Apple4()
{
	cout << "Apple4 Created!" << endl;
}

Apple4::~Apple4()
{
};

void Apple4::ShowVersion()
{
	cout << "I‘m Apple4" << endl;
}

void Apple4::MakeCall(const std::string &num)
{
	cout << "I‘m Call num :" << num << endl;
}

Apple4s.h

#pragma once
#include "Apple.h"

class Apple4s : public Apple
{
public:
	Apple4s();
	~Apple4s();

	virtual void ShowVersion();
	virtual void MakeCall(const std::string &num);
};

Apple4s.cpp

#include "Apple4s.h"
#include <iostream>
#include <string>

using namespace std;

Apple4s::Apple4s()
{
	cout << "Apple4s Created!" << endl;
}

Apple4s::~Apple4s()
{
};

void Apple4s::ShowVersion()
{
	cout << "I‘m Apple4s" << endl;
}

void Apple4s::MakeCall(const std::string &num)
{
	cout << "I‘m Call num :" << num << endl;
}

AppleFactory.h

#pragma once 
#include "Apple.h"
#include <string>

class AppleFactory
{
public:
	AppleFactory();
	~AppleFactory();

	static Apple * MakePhone(const std::string &version);//声明为静态成员函数

};

AppleFactory.cpp

#include "AppleFactory.h"
#include "Apple4.h"
#include "Apple4s.h"
#include <iostream>
#include <string>

AppleFactory::AppleFactory()
{
}

AppleFactory::~AppleFactory()
{
}

Apple * AppleFactory::MakePhone(const std::string &version)
{
	if(version == "Apple4")
	{
		return new Apple4();
	}
	if(version == "Apple4s")
	{
		return new Apple4s();
	}
	return NULL;
}

main.cpp
#include "AppleFactory.h"
#include <iostream>

int main()
{
	Apple * A4 = AppleFactory::MakePhone("Apple4");
	A4->ShowVersion();
	A4->MakeCall("10086");

	std::cout << "------------------" << std::endl;

	Apple * A4s = AppleFactory::MakePhone("Apple4s");
	A4s->ShowVersion();
	A4s->MakeCall("10010");
	
	return 0;
}

/*
执行结果:

Apple4 Created!
I‘m Apple4
I‘m Call num :10086
------------------
Apple4s Created!
I‘m Apple4s
I‘m Call num :10010
请按随意键继续. . .
*/

这个模式也叫静态工厂模式,由于依赖的是工厂类中的静态方法。



设计模式C++实现_2_简单工厂模式