top of page

Design pattern – strategy for C++

Hi!

Now we want to talk about design patterns. We can add weapon, but how? Inherit weapon inside warrior? Not, inheriting it not resolving for this problem because you can want to change weapon like warrior with axe -> warrior with two hand sword or archer -> crossbowman. You can always make an additional object container for second weapon slot etc.

weapon.h

class Weapon {

protected:

int attack;

string name

public:

weapon(int, string);

int getAttackPower();

}

weapon.cc

weapon::weapon(int weaponPower, string weaponPower) { attack = weaponPower;

name = weaponName; }

weapon::getAttackPower() { return attack; }

warrior.h

---------------------------------------

#pragma once

#include "human.h"

class warrior : public human

{

public:

Weapon weaponFirstSlot; ß

Weapon weaponSecondSlot; ß

warrior();

~warrior();

void move(int);

void attack(human*);

};

---------------------------------------

warrior.cc

---------------------------------------

#include "warrior.h"

warrior::warrior()

{

Weapon dagger(5,”Dagger”);

weaponFirstSlot = dagger;

weaponSecondSlot = dagger;

}

warrior::~warrior()

{

}

void warrior::move(int steps)

{

position += steps;

}

void warrior::attack(human* man)

{

man->getHit(10 + weaponFirstSlot.getAttackPower() + weaponSecondSlot.getAttackPower());

}

---------------------------------------

As you see it is not hard to implement, but you need to think about how you can use it. Design patterns are very useful, but most of them I had to design by myself because I was not read about it earlier. From few months with knowledge about design patterns I spend less time on thinking about resolutions. We can of course create place for weapons in human and there it will be the best place to make it, but I wanted just show you how it can be used. It was not designed – it was example. Bye!

Subscribe me!

Be sure that you read all.

  • Facebook Clean
  • Black Twitter Icon
  • Black Instagram Icon
  • Black YouTube Icon
Recent Posts
bottom of page