首页 > 解决方案 > 我怎样才能最好地解耦两个类,其中一种方式依赖

问题描述

我正在尝试使用 C++ 创建一个 D&D 战斗遭遇模拟器,因为它是 D&D,所以模拟的所有方面都将严重依赖于“Dice”类及其方法。每次另一个类需要调用它的方法时,我都可以实例化一个“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

演员.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

标签: c++classdesign-patternsdecoupling

解决方案


您在问题中谈论单例等,那么您是否希望需要使用骰子的类使用 Dice 类的相同实例?

如果是这样,因为 Dice 类没有任何状态可以保留它可以是一个静态类。然后我会删除 MaxValue 并向 RollDice 和 RollMutiDice 添加一个输入以获取最大值(我猜这是假设骰子的“边”)。所以调用 Dice::RollDice(3) 是掷一个 3 面骰子或 Dice::RollMutiDice(6,3) 将掷一个 6 面骰子 3 次。

还要确保发送 rand() 类。我认为是 srand(int)。通常你会打发时间,所以它是相当随机的


推荐阅读