制作高度可定制的方法,或执行任务的特定方法?

Making a highly customizable method, or a specific method that does a task?

我不太确定如何正确表述标题,所以对于最初的混淆,我深表歉意。

这只是我对如何构建代码等的一个小问题,我不知道如何称呼它,所以我将用这个例子来解释它:

假设我正在编写一个使命召唤类型的游戏,玩家可以在其中自定义带有特定附件的武器。

我有一个 class 来定义每把枪。它看起来像这样:

class Gun {

int clip = 30;
int ammo = 100;
float reloadTime = 5f;
float damage = 10f;
Attachment[] attachments;
//Plus some not included attachments.

void shoot() {
  //...
}

void reload() {
  //...
}

void applyAllAttachments() {
  //Apply the list of attachments' effects
}

}

class Attachment {
void effect() {
//change the gun in some way.
}

}

现在我想添加 4 个附件,Fast Mags(增加装填速度),Hollow Point(增加伤害),Grenade Launcher(副枪)和 Minigun(用 minigun 或其他东西替换枪管)。

对于Fast Mags和Hollow Point,应该很简单,我所要做的就是更改一个数字或一个值,但是对于Grenade Launcher和Minigun,它们具有自定义的额外功能(例如Unity Delegates ), 添加一个处理外部自定义射击类型的函数会更明智,还是在 Gun class 中使用单独的方法来专门处理额外的 minigun 函数会更好?

TL;DR

如果我想给枪加一个榴弹发射器附件,我应该这样做吗:

class Gun {

int clip = 30;
int ammo = 100;
float reloadTime = 5f;
float damage = 10f;
Attachment[] attachments = Attachment[10];
//Plus some not included attachments.

void shoot() {
  //...
  customShoot();
}
void customShoot() {
    //Apply attachments custom attachment shoot methods.
}

void reload() {
  //...
}

void applyAllAttachments() {
  //Apply the list of attachments' effects
}

}

class GrenadeLauncher extends Attachment {
@Override
public void effect() {
//Spawn new grenade
}

}

或者这个:

class Gun {

int clip = 30;
int ammo = 100;
float reloadTime = 5f;
float damage = 10f;
Attachment[] attachments = Attachment[10];
//Plus some not included attachments.

void shoot() {
  //...
  if (attachments.GetType() == GrenadeLauncher) {
      grenadeLauncherShoot();
  }
}
void grenadeLauncherShoot() {

}

void reload() {
  //...
}

void applyAllAttachments() {
  //Apply the list of attachments' effects
}

}

抱歉我的 pseudo/java 代码,希望它是可以理解的。

第一种方法更好:您可以创建新附件而无需修改 Gun class。

一般情况下,您不需要检查类型,如果不检查,您的代码会更简洁。

在这里,您的附件 class 应该是抽象的(我想它已经是),并强制 children 实现一些功能。

public abstract class Attachment
{
    protected abstract void shoot();
}

然后枪为所有附件调用它:

class Gun {
    int clip = 30;
    int ammo = 100;
    float reloadTime = 5f;
    float damage = 10f;
    Attachment[] attachments = Attachment[10];
    //Plus some not included attachments.

    void shoot() {
        //...
        for(int i = 0; i < attachments.length(); ++i) {
            attachments[i].shoot();
        }
    }

    void reload() {
      //...
    }
}

class GrenadeLauncher extends Attachment {
    @Override
    public void shoot() 
    {
        //Spawn new grenade
    }
}

对了,你为什么要标记java和Unity?如果您使用 unity,您的代码应该是 c# 或 javascript