C++ 简单设计模式之简单工厂

一、简单工厂

一个工厂类能够根据传入参数而决定创建出哪一种产品类的实例

二、类设计

// 手机
class Phone {
public:
	virtual void model() = 0;
};

// 华为手机
class HuaWei : public Phone {
public:
	void model() {
		cout << "HuaWei" << endl;
	}
};

// 小米手机
class XiaoMi : public Phone {
public:
	void model() {
		cout << "XiaoMi" << endl;
	}
};

// 苹果手机
class Apple : public Phone {
public:
	void model() {
		cout << "Apple" << endl;
	}
};

// 生产手机的工厂
class PhoneFactory {
public:
	Phone* createPhone(int phone_type) {
		switch (phone_type)
		{
		case 0: m_phone = new HuaWei(); break;
		case 1: m_phone = new XiaoMi(); break;
		case 2: m_phone = new Apple();  break;

		default:
			m_phone = nullptr; break;
		}

		return m_phone;
	}
private:
	Phone *m_phone;
};

三、使用方式

int main(int argc, char *argv[])
{
	Phone *phone = nullptr;
	PhoneFactory *factory = new PhoneFactory();

	return 0;
}

1、生产产品

int main(int argc, char *argv[])
{
	Phone *phone = nullptr;
	PhoneFactory *factory = new PhoneFactory();

	// 生产华为手机
	phone = factory->createPhone(0);
	phone->model();

	delete phone;

	return 0;
}

2、生产产品

int main(int argc, char *argv[])
{
	Phone *phone = nullptr;
	PhoneFactory *factory = new PhoneFactory();

	// 生产小米手机
	phone = factory->createPhone(1);
	phone->model();

	delete phone;

	return 0;
}

3、生产产品

int main(int argc, char *argv[])
{
	Phone *phone = nullptr;
	PhoneFactory *factory = new PhoneFactory();

	// 生产苹果手机
	phone = factory->createPhone(2);
	phone->model();

	delete phone;

	return 0;
}

四、完整代码

#include <iostream>
using namespace std;

// 手机
class Phone {
public:
	virtual void model() = 0;
};

// 华为手机
class HuaWei : public Phone {
public:
	void model() {
		cout << "HuaWei" << endl;
	}
};

// 小米手机
class XiaoMi : public Phone {
public:
	void model() {
		cout << "XiaoMi" << endl;
	}
};

// 苹果手机
class Apple : public Phone {
public:
	void model() {
		cout << "Apple" << endl;
	}
};

// 生产手机的工厂
class PhoneFactory {
public:
	Phone* createPhone(int phone_type) {
		switch (phone_type)
		{
		case 0: m_phone = new HuaWei(); break;
		case 1: m_phone = new XiaoMi(); break;
		case 2: m_phone = new Apple();  break;

		default:
			m_phone = nullptr; break;
		}

		return m_phone;
	}
private:
	Phone *m_phone;
};


int main(int argc, char *argv[])
{
	Phone *phone = nullptr;
	PhoneFactory *factory = new PhoneFactory();

	// 生产华为手机
	phone = factory->createPhone(0);
	phone->model();
	delete phone;

	// 生产小米手机
	phone = factory->createPhone(1);
	phone->model();
	delete phone;

	// 生产苹果手机
	phone = factory->createPhone(2);
	phone->model();
	delete phone;

	return 0;
}

posted @ 2022-08-31 11:15  想想就很离谱  阅读(37)  评论(0编辑  收藏  举报