gpt4 book ai didi

java - 根据构造函数的参数使用不同的方法

转载 作者:行者123 更新时间:2023-11-30 08:48:18 24 4
gpt4 key购买 nike

我有一个类,根据传递给类构造函数的参数,该类的方法实现应该略有不同。但是,我想选择在创建对象时运行哪个实现,而不是总是测试指定的参数。这种东西:

public class SomeClass(){
int parameter=-1;

SomeClass(int param){
this.parameter = param;
}

public methodSpecific(){ //For when parameter==1;
Do stuff...
}

public methodSpecific(){ //For when parameter==2;
Do stuff...
}
}

代替:

public class SomeClass(){
int parameter=-1;

SomeClass(int param){
this.parameter = param;
}

public methodForAll(){
switch(parameter){
case 1:
Do something...

case 2:
Do something else...
}
}
}

有什么方法可以实现吗?

编辑:此编辑是为了澄清情况和上下文。请考虑下图。相同颜色的矩形表示这些方法的实现是相同的。不同颜色的矩形意味着即使名称相同,实现也不同。我需要找到一种方法来实现 classA 和 classB,但没有重复的代码,并且仍然允许类“main”知道 classA 和 classB 都具有相同的方法名称和变量。

Ilustrative figure

最佳答案

我首先想到的是,直接但不想要的实现是拥有 SomeClass 的两个子类,但需要说明的是这实际上是您想要的。我仍然编辑了我的示例以符合问题的新旧版本;-)

这个想法是将不同的实现隐藏到一组匿名类中,这些匿名类实现了公共(public)基类的抽象方法。基类是已知的,由 runMethod1() 和 runMethod2() 调用,使用哪个实现在 SomeClass 的构造时决定。

例子:

public class SomeClass()
{
private abstract class BasicStuff
{
// All code that is the same in all implementations go here
void method1() { /* do something that is always the same */ }

// All code that shall be different in all implementations go here
abstract void method2();
}

private final BasicStuff whatShallWeDoToday;

public SomeClass(int param)
{
switch (param)
{ // construct anonymous class with functionallity of ClassA
case 1: whatShallWeDoToday = new StuffInterface()
{
void method2() { /* something */ }
}
break;

// construct anonymous class with functionallity of ClassB
case 2: whatShallWeDoToday = new StuffInterface()
{
void method2() { /* something else */ }
}
break;

default:throw IllegalArgumentException();
}
}

public runMethod1()
{
whatShallWeDoToday.method1();
}

public runMethod2()
{
whatShallWeDoToday.method2();
}
}

关于java - 根据构造函数的参数使用不同的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32038774/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com