工厂模式+策略模式优化大量if-else

工厂模式+策略模式优化大量if-else


在项目中常常会碰到大量的if-else的情况,尤其是一个类中还分好几种情形

class world
{
public: 
	char m_professional[32];
	
	world(const char *person)
	{
		strncpy(m_professional,person,sizeof(m_professional));
	}
	~world()
	{
		memset(m_professional,0x00,sizeof(m_professional));
	}
	bool AreYou(const char *professional)
	{
		retrun (strcmp(this->m_professional,professional)==0)
	}
	
	void do()
	{
		if(AerYou("thief"))
		{
			cout << "Steal things" << endl;
		}
		esle if(AerYou("police"))
		{
			cout << "catch thief" << endl;
		}
	}
}

void main()
{
	//
	world firstday = new world("thief");
	firstday.do();
	delete firstday;
	
	world secondday = new world("police");
	secondday.do();
	delete secondday;
	return;
}

优化后的方法

// 基类
class person
{
public:
	virtual void do();
}
// 子类
class police:public person
{
public:
	void do()
	{
		cout << "catch thief" << endl;
	}
}
class thief:public person
{
public:
	void do()
	{
		cout << "Steal things" << endl;
	}
}
// 策略类
class world
{
public:
	person *m_Person;

public:
	world(person *p)
	{
		m_Person = p;
	}
	~world()
	{
		delete m_Person;
	}
	void event()
	{
		m_Person->do();
	}
}


//实现
void main
{
	//第一天出现了一个小偷
	world fristday = new world(new thief());
	fristday.event();
	//事件是Steal things
	delete fristday;
	//第一天结束了
	
	//第二天出现了一个警察
	world secondday = new world(new police());
	fristday.event();
	//事件是catch thief
	delete secondday;
	//第二天结束了
	return;
}

如有错误欢迎指正

你可能感兴趣的:(工厂模式+策略模式优化大量if-else)