【发布时间】:2020-09-05 18:12:51
【问题描述】:
我正在尝试使用 C++ 创建一个 D&D 战斗遭遇模拟器,因为它是 D&D,所以模拟的所有方面都将严重依赖于“Dice”类及其方法。 每次另一个类需要时,我都可以实例化一个“骰子”对象 然而,调用它的方法,这将使一切变得沉重 耦合并使得以后很难进行更改或扩展。
我对诸如工厂、依赖注入和其他此类方法之类的东西没有任何实际知识。 因此,我的问题本质上是:
确保“骰子”类保持不变的最佳方法是什么 尽可能与所有其他类解耦? 同时仍使他们能够在需要时使用“骰子”对象及其方法。
骰子.h
#ifndef dice_h_
#define dice_h_
#include <stdlib.h>
class Dice
{
private:
int maxValue;
public:
Dice(int maxValue);
~Dice();
int getMaxValue( void ){return maxValue;}
void setMaxValue(int newMaxValue){maxValue = newMaxValue;}
int rollDice();
int rollMultipleDice(int numberOfDiceRolls);
};
#endif
骰子.cpp
#ifndef dice_cpp_
#define dice_cpp_
#include "dice.h"
Dice::Dice(int maxValue){this->maxValue = maxValue;}
Dice::~Dice(){}
int Dice::rollDice()
{
return (rand() % maxValue) + 1;
}
int Dice::rollMultipleDice(int numberOfDiceRolls)
{
int i = numberOfDiceRolls, sum = 0;
while(i-- > 0)
{
sum += rollDice();
}
return sum;
}
#endif
演员.h
#ifndef actor_h_
#define actor_h_
#include "dice.h"
class Actor
{
private:
unsigned int hp;
unsigned int ac; // Armor Class
unsigned int dmg;
public:
Actor(unsigned int hp, unsigned int ac, unsigned int dmg);
~Actor();
unsigned int getHP( void );
unsigned int getAC( void );
unsigned int getDmg( void );
void setHP( unsigned int newHP);
void setAC( unsigned int newAC);
void setDmg( unsigned int newDmg);
void attack(Actor* target);
bool isHit(Actor target);
};
#endif
Actor.cpp
#ifndef actor_cpp_
#define actor_cpp_
#include "actor.h"
Actor::Actor(unsigned int hp, unsigned int ac, unsigned int dmg)
{
this->hp = hp;
this->ac = ac;
this->dmg = dmg;
}
Actor::~Actor(){}
unsigned int Actor::getHP( void ){return hp;}
unsigned int Actor::getAC( void ){return ac;}
unsigned int Actor::getDmg( void ){return dmg;}
void Actor::setHP( unsigned int newHP ){this->hp = newHP;}
void Actor::setAC( unsigned int newAC ){this->ac = newAC;}
void Actor::setDmg( unsigned int newDmg ){this->dmg = newDmg;}
void Actor::attack(Actor* target)
{
Dice damageDice(8);
if (isHit(*target))
{
target->setHP(target->getHP() - damageDice.rollDice());
}
}
// helper function to attack function
// do not use elsewhere
bool Actor::isHit(Actor target)
{
Dice atkDice(20);
return atkDice.rollDice() >= target.getAC();
}
#endif
【问题讨论】:
-
你的
Dice对Actor没有依赖,不清楚你要解耦什么 -
通常,
*.cpp文件不是#include'd,因此您不需要为它们提供标头保护。 -
@idclev463035818 我的意思是,如果我每次需要使用 Dice 时都实例化它(就像我在 Actor::attack 中所做的那样)。然后,如果我稍后更改 Dice,通过添加字段或更改构造函数,我将破坏创建 Dice 实例的每个类或函数。
标签: c++ class design-patterns decoupling