top of page

Design pattern – adapter for C++

Welcome on last design topic for C++ only. I guess design patterns are interesting for everyone and I will prepare more topics about design in the design tab. If you want to have more examples – tell me what you want I am able on facebook, youtube, deviantart known as AppleTree (EN) and Czester16 (PL/EN). As AppleTree I don’t start many sites, so Czester16 can be easier to find.

So what is adapter? Adapter is kind of object which connect two different objects. For example we have a human -> warrior and elf -> mage. As you saw before human have function attack, but elf mage don’t have that functionality, he can only use spells. So we can make simple skeletons in C++.

Human.h

 

#pragma once

class human

{

public:

virtual void attack(human*)=0;

int getHealth();

void getHit(int);

protected:

int health = 100;

};

 

Elf.h

 

#pragma once

class elf

{

public:

virtual void spell(human*)=0;

int getHealth();

void getHit(int);

protected:

int health = 50;

};

 

As you can see classes are similar, but not same. That is why when we want to put elf to our company which is created from peoples you need to make something...

ElfToHumanAdapter.h

 

#pragma once

class elf : public human

{

public:

ElfToHumanAdapter(elf);

void attack(human*);

private:

elf ElfCreature;

};

 

ElfToHumanAdapter.cc

 

#include “ElfToHumanAdapter.h”

ElfToHumanAdapter:: ElfToHumanAdapter(elf OriginalElf) {

ElfCreature = OriginalElf;

}

void ElfToHumanAdapter::attack(human* man){

ElfCreature.spell(man);

}

 

It is not best way of use it, because we want to use it just when we have different systems like game engine and steam api which I needed to implement it in my game. But we prepare example - simple code for understanding process of thinking.

Now we can have table of humans with our elf.

warrior Romek;

elf Tomek;

ElfToHumanAdapter ElfInAdapter(Tomek);

tableOfHumans[0] = Romek;

tableofHumans[1] = ElfInAdapter;

Creating that way of work you can manage object with different types in one smarter way. Have a nice day!

Subscribe me!

Be sure that you read all.

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