首页 > 代码库 > Design Pattern 设计模式1 - Strategy 1

Design Pattern 设计模式1 - Strategy 1

实现 : Defferent Heros attack Defferently. - 不同的英雄使用不用的招数


Strategy设计的思路:

基类A,更加小的基类B,新的继承类C:

1 从基类A中抽出一个更加小的基类B

2 利用这个更加小的基类B实现不同的效果

3 把这个更加小的基类B包含进基类A中去

4 新的继承类C只需要和基类A打交道,设计不同行为,不需要理会更加小的基类B


#pragma once
#ifndef _STRATEGY_HEROS_H
#define _STRATEGY_HEROS_H

#include <stdio.h>

//Interface
class HeroAttack
{
public:
	virtual void attack() = 0;
};

//Base method class
class Laser : public HeroAttack
{
public:
	void attack()
	{
		puts("Super Eye-Laser");
	}
};

class Smash : public HeroAttack
{
public:
	void attack()
	{
		puts("I smash!");
	}
};

class WebWebWeb : public HeroAttack
{
public:
	void attack()
	{
		puts("Web, Web, Web!");
	}
};

//Base Class
class Hero_From_Marvel
{
	HeroAttack *heroAtt;
protected:
	void setAttackWay(HeroAttack *hat)
	{
		if (heroAtt) delete heroAtt;
		heroAtt = hat;
	}
public:
	Hero_From_Marvel() : heroAtt(nullptr)
	{
	}

	virtual ~Hero_From_Marvel()
	{
		if (heroAtt) delete heroAtt;
		heroAtt = nullptr;
	}

	void attack()
	{
		heroAtt->attack();
	}
};

//derived class
class SuperMan : public Hero_From_Marvel
{
public:
	SuperMan()
	{
		setAttackWay(new Laser);//这里不能使用malloc,否则内存冲突
	}
};

class Hulk : public Hero_From_Marvel
{
public:
	Hulk()
	{
		setAttackWay(new Smash);
	}
};

class SpiderMan : public Hero_From_Marvel
{
public:
	SpiderMan()
	{
		setAttackWay(new WebWebWeb);
	}
};

int StrategyHerosRun()
{
	const int HEROS = 3;
	Hero_From_Marvel *hfm[HEROS] = {new SuperMan, new Hulk, new SpiderMan};
	for (int i = 0; i < HEROS; i++)
	{
		hfm[i]->attack();
		delete hfm[i];
	}
	return 0;
}

#endif