在一个函数中使用两组常量。

huangapple go评论65阅读模式
英文:

use two sets of constants in one function

问题

我有一个函数,在两种不同的情况下我想要使用两组不同的常量。例如:在其中一种情况下,我想要使用

private final class MoveOverTarget
{
    private final int SPEED = 3000;
    private final int SLOW_SPEED = 0;
    private final float D_B_SLOW_REGION = 0;
    public final float D_B_TARGET_RANGE = 0;
}

而在另一种情况下,我想要使用

private final class MoveTowardsTarget
{
    private final int SPEED = 1000;
    private final int SLOW_SPEED = 500;
    private final float D_B_SLOW_REGION = 50;
    public final float D_B_TARGET_RANGE = 10;
}

对于同一个函数

private boolean bValInTargetRange(float targetValue, boolean moveOverTarget)
{}

目前我无法想出一个易于实现的解决方案,也无法找到正确的关键词在谷歌上搜索。你能帮帮我吗?

提前感谢。

英文:

I have a function for which in two different situations I want to use two different sets of constants. Eg:in one i want to use

private final class MoveOverTarget
	{
		private final int SPEED = 3000;
		private final int SLOW_SPEED = 0;
		private final float D_B_SLOW_REGION = 0;
		public final float D_B_TARGET_RANGE = 0;
	}

and in another

private final class MoveTowardsTarget
	{
		private final int SPEED = 1000;
		private final int SLOW_SPEED = 500;
		private final float D_B_SLOW_REGION = 50;
		public final float D_B_TARGET_RANGE = 10;
	}

for the same function

private boolean bValInTargetRange(float targetValue, boolean moveOverTarget)
	{}

at the moment i can't think about an easy to implement solution and don't seem to find the correct keywords for google. Can you help me out?

Thanks in advance.

答案1

得分: 1

将它们设为public static

public static final int SPEED = 3000;

并使用类名引用它们:

MoveOverTarget.SPEED
MoveTowardsTarget.SPEED

还要考虑是否使用enum会更好。另一种选择:在每个类中定义两份方法副本,然后在方法中引用该类中的常量。

还有一种选择:定义一个抽象的父类,在父类中编写方法并通过抽象方法访问常量。然后定义两个子类,在每个子类中实现返回不同常量值的抽象方法,这些常量也在每个子类中定义。

英文:

Make them public static:

public static final int SPEED = 3000;

And refer to them using the class name:

MoveOverTarget.SPEED
MoveTowardsTarget.SPEED

Also consider if using enums would be better. Another option: define two copies of the method, one in each class, and refer to the constants from that class in the method.

Yet another option: define an abstract superclass, write the method there and access the constants with abstract methods. Then define two subclasses, and in each one implement the abstract methods that return different values for the constants, also defined in each of the subclasses.

huangapple
  • 本文由 发表于 2020年10月2日 20:09:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/64171303.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定