UML和設計模式——簡單工廠模式、工廠模式

簡單工廠模式

簡單工廠模式通過定義一個類來創建其他類的實例。但不是標準的設計模式

當需求發生變化時需要修改代碼 不符合開閉原則

簡單工廠模式分三種角色:
1.工廠角色
2.抽象角色
3.具體角色

在這裏插入圖片描述
抽象角色是具體角色的父類

#include<iostream>
using namespace std;
class Person
{
public:
	virtual void work() = 0;
};
class Student:public Person
{
public:
	virtual void work()
	{
		cout << "go to school" << endl;
	}
};
class Teacher :public Person
{
public:
	virtual void work()
	{
		cout << "teach students" << endl;
	}
};
class Factory
{
public:
	Person* getPerson(string type)
	{
		if (type == "student")
		{
			return new Student;
		}
		else if (type == "teacher")
		{
			return new Teacher;
		}
	}

};

int main()
{
	string type;
	Factory* f = new Factory;
	Person* p = nullptr;

	type = "student";
	p = f->getPerson(type);
	p->work();
	type = "teacher";
	p = f->getPerson(type);
	p->work();
	delete p;
	delete f;


	return 0;
}

工廠模式

符合開閉原則的工廠模式:
此時有新的需求只需要增加代碼不需要修改代碼
1.創建新的工廠繼承於抽象工廠
2.創建新的產品繼承於抽象產品
3.使用新的工廠創建新的產品

在這裏插入圖片描述

#include<iostream>
using namespace std;
class Fruit
{
public:
	virtual void sayname() = 0;
};
class Apple :public Fruit
{
public:
	virtual void sayname()
	{
		cout << "apple" << endl;
	}
};
class Orange :public Fruit
{
public:
	virtual void sayname()
	{
		cout << "orange" << endl;
	}
};

class AbsFactory
{
public:
	virtual Fruit* CreateFruit() = 0;
};
class AppleFactory:public AbsFactory
{
public:
	virtual Fruit* CreateFruit()
	{
		return new Apple;
	}
};
class OrangeFactory:public AbsFactory
{
public:
	virtual Fruit* CreateFruit()
	{
		return new Orange;
	}
};

//新增品種
class NewFruit:public Fruit
{
public:
	virtual void sayname()
	{

		cout << "NewFruit" << endl;
	}
};
class NewFactory:public AbsFactory
{
public:
	virtual Fruit* CreateFruit()
	{
		return new NewFruit;
	}
};


int main()
{
	Fruit* fruit = nullptr;
	AbsFactory* absf = nullptr;

	absf = new AppleFactory;
	fruit = absf->CreateFruit();
	fruit->sayname();

	delete absf;
	delete fruit;
	absf = nullptr;
	fruit = nullptr;

	absf = new OrangeFactory;
	fruit = absf->CreateFruit();
	fruit->sayname();

	delete absf;
	delete fruit;
	absf = nullptr;
	fruit = nullptr;

	absf = new NewFactory;
	fruit = absf->CreateFruit();
	fruit->sayname();


	delete absf;
	delete fruit;
	absf = nullptr;
	fruit = nullptr;

	return 0;
}

發佈了7 篇原創文章 · 獲贊 0 · 訪問量 420
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章