作者:jx轩宝妈咪 | 来源:互联网 | 2022-12-06 19:15
我最初创建了一个包含将在两个类之间共享的所有方法的接口,但是,我意识到我希望这两个类具有相同的方法,但它们的行为会有所不同.
它们具有相同的返回类型,但参数不同.我无法弄清楚如何实现这一点,或者即使我确实弄清楚如何实现这一点,我不知道它是否是处理这种情况的正确方法
基本上,我来到这里寻找正确的架构方法来解决我想要完成的事情,我不知道那会是什么.我想我有4个问题来确定代码架构:
这是一个正确的接口,如果是这样,为什么?
这是一个抽象类正确的方法,如果是这样的话为什么呢?
这似乎是OOP的一个共同主题,我的意思是拥有一个函数,你可以在特定的类中表现出不同的行为.如何设计代码?
最后,我的第一个想法是,"哦,我将覆盖其中一个类中的方法",但这给了我一个巨大的麻烦,并没有工作.我觉得在尝试覆盖方法时我从未遇到过这种麻烦.从界面覆盖一个方法更复杂?
public interface Character {
public void setAttack();
}
/*the setAttack method here will be set by the programmer. The 3 values
passed by the programmer are then stored into an array*/
public class Player implements Character {
public void setAttack(int x, int y, int z) {
attackArray[0] = x;
attackArray[1] = y;
attackArray[2] = z;
}
}
/*the setAttack will still serve the same purpose as the setAttack in the
player class, however, the values will be auto generated randomly once the
setAttack function is called for the NPC instance.*/
/*Another thought I had is passing the function that auto generates the 3
integer values (numGen()) as a parameter 3 times, however, I'm not sure if
this is possible. Just a thought*/
public class NPC implements Character {
public void setAttack(){
for(int i = 0; i
GhostCat say..
6
存在一个概念上的误解:使用相同的方法不仅仅意味着实现具有相同名称的方法.
当您在Java中使用多态和接口时,您就表达了意图.如:实现某些接口的类必须提供相应的"功能".换句话说:这描述了某种行为.
事情是:当界面有foo()
,并且不同的类可能想要一个foo(X)
,foo(Y)
然后真正的问题是:这些方法有多个共同点而不仅仅是名称?!
如果是这样,一个可能的解决方案将是另一层抽象.在你的情况下,像:
public interface AttackParameters {
...
public interface Character {
public void setAttack(AttackParameters parms);
或类似的东西.我们的想法是再次用通用解决方案替换"特定"细节.
或者,您可以Map
为setAttack()
方法使用参数.换句话说:攻击参数由字符串标识.
这很好,很动态,但它也避免了编译时的安全性.稍微好一点的map方法不会使用Strings作为键,而是使用一些枚举类.
1> GhostCat say..:
存在一个概念上的误解:使用相同的方法不仅仅意味着实现具有相同名称的方法.
当您在Java中使用多态和接口时,您就表达了意图.如:实现某些接口的类必须提供相应的"功能".换句话说:这描述了某种行为.
事情是:当界面有foo()
,并且不同的类可能想要一个foo(X)
,foo(Y)
然后真正的问题是:这些方法有多个共同点而不仅仅是名称?!
如果是这样,一个可能的解决方案将是另一层抽象.在你的情况下,像:
public interface AttackParameters {
...
public interface Character {
public void setAttack(AttackParameters parms);
或类似的东西.我们的想法是再次用通用解决方案替换"特定"细节.
或者,您可以Map
为setAttack()
方法使用参数.换句话说:攻击参数由字符串标识.
这很好,很动态,但它也避免了编译时的安全性.稍微好一点的map方法不会使用Strings作为键,而是使用一些枚举类.