添加新弦的调制->方法调用

发布于 2024-10-18 20:34:08 字数 484 浏览 2 评论 0原文

如果我有一个执行以下操作的程序:

if(input=='abc'){do x}
if(input=='def'){do y}

将来,我可能想添加另一段代码,如下所示:

if(input=='ghy'){do x}

如您所见,我正在为不同的条件添加新的“if”语句,但使用相同的函数 X 。 未来的代码可能会包含许多不同的 IF 语句(或开关),所有这些语句都会比较字符串与字符串,然后执行函数。考虑到未来的扩展,我想知道是否有一种可能的“更整洁”、“模块化”的方式来实现相同的结果。

遗憾的是我无法将字符串与 Java 中的哈希表(字符串,方法)中的方法调用结合起来。这样我就可以将任何新过程存储在哈希表中并获取该字符串的相关方法。

有什么想法吗?

谢谢

编辑:谢谢大家的解决方案。我对在如此短的时间内收到的回复的数量和质量感到惊讶。

If I have a program that does the following:

if(input=='abc'){do x}
if(input=='def'){do y}

In the future, I may want to add another piece of code like so:

if(input=='ghy'){do x}

As you can see, I am adding a new 'if' statement for a different conditional BUT using the SAME function X.
The code in future has potential to have lots of different IF statements (or switches) all of which are comparing a string vs a string and then performing a function. Considering the future expansion, I was wondering if there is a possible 'neater', 'modular' way of achieving the same results.

It's a shame I can't combine the String with a Method call in a hashtable (String, method) in Java. That way I could just store any new procedures inside a hashtable and grab the relevant method for that String.

Any ideas?

Thank you

EDIT: Thank you for everyone's solutions. I was surprised by the quantity and quality of replies I received in such a small amount of time.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

爱你不解释 2024-10-25 20:34:08

也许你可以使用enum。示例:

public enum InputType
{

    abc, def
    {
        @Override
        public void x()
        {
            System.out.println("Another method");
        }
    },
    ghy;

    public void x()
    {
        System.out.println("One method");
    }
}

进一步:

InputType.valueOf("abc").x();

干杯!

Maybe you can use enum. Example:

public enum InputType
{

    abc, def
    {
        @Override
        public void x()
        {
            System.out.println("Another method");
        }
    },
    ghy;

    public void x()
    {
        System.out.println("One method");
    }
}

And further:

InputType.valueOf("abc").x();

Cheers!

时常饿 2024-10-25 20:34:08

我想你总是可以使用 Map并映射到匿名 Runnable 实现:

myMap.put("abc", new Runnable() { public void run() { do x } });

...

myMap.get(input).run();

I guess you could always use a Map<String, Runnable> and map to anonymous Runnable implementations:

myMap.put("abc", new Runnable() { public void run() { do x } });

...

myMap.get(input).run();
相思故 2024-10-25 20:34:08

您应该看一下命令模式。有多种实现方法,Spring 等框架可以帮助您以干净的方式实现。

但您可以简单地执行以下操作:

1-创建一个 Command 接口,其中包含程序必须调用的方法来执行任务,例如 doTask()

2-为命令 X 和 Y 创建类,实现 Command 接口。

3-创建一个Map,将您的命令(X 和 Y)映射到逻辑名称

4-创建您选择的配置文件,例如将映射您的输入的 .properties 文件到您的命令名称:abc=X、def=Y、ghi=X

5-您的程序然后在配置文件上查找以了解根据输入运行哪个命令。

You should take a look at the command pattern. There are several ways of implementing it, and frameworks such as Spring can help you do with in a clean way.

But in a simple manner here's what you could do:

1-Create a Command interface with a method that your program will have to call to do the task, say doTask()

2-Create classes for command X and Y, implementing the Command interface.

3-Create a Map<String, Command> that will map your commands (X and Y) to logical names

4-Create a configuration file of your choice, say a .properties file that will map your input to your command names: abc=X, def=Y, ghi=X

5-Your program then does lookups on the config file to know which command to run according to the input.

寄居人 2024-10-25 20:34:08

很多如果总是告诉我们我们可以做得更好。在您的情况下,更好的选择是使用设计模式,例如责任链。您将拥有可以动态更改的良好实现,并且您的代码将比 ifs 实现更易于维护。

看一下您的案例的适应责任链:

Main:

public static void main(String[] args) {
    ClassA classA = new ClassA(Arrays.asList("abc", "ghi"));
    ClassB classB = new ClassB(Arrays.asList("def"));
    classA.setNextInChain(classB);  // you can always write Builder to do this
    String input = "def";
    classA.execute(input);
}

BaseClass:

public abstract class BaseClass {
    private Collection<String> patterns = Collections.EMPTY_LIST;
    protected BaseClass nextInChain;
    protected abstract void doMethod();  // your doA, doB methods

    public void execute(String input) {
            // this replace many ifs in your previous implementation
        if (patterns.contains(input)) {
            doMethod();
        } else {
            nextInChain.execute(input);
        }       
    }

    public void setPatterns(Collection<String> patterns) {
        this.patterns = patterns;
    }

    public void setNextInChain(BaseClass nextInChain) {
        this.nextInChain = nextInChain;
    }
}

链中的类:

public class ClassA extends BaseClass {
    ClassA(Collection<String> patterns) {
        setPatterns(patterns);
    }
    @Override
    protected void doMethod() {
        // do A     
    }
}

public class ClassB extends BaseClass {...}

A lot of ifs always tell us that we could do this better. In your case better option is to use design pattern e.g. Chain of responsibility. You will have good implementation which you can dynamic change and your code will be easier to maintenance than ifs implementation.

Take a look at this adaptation chain of responsibility to your case:

Main:

public static void main(String[] args) {
    ClassA classA = new ClassA(Arrays.asList("abc", "ghi"));
    ClassB classB = new ClassB(Arrays.asList("def"));
    classA.setNextInChain(classB);  // you can always write Builder to do this
    String input = "def";
    classA.execute(input);
}

BaseClass:

public abstract class BaseClass {
    private Collection<String> patterns = Collections.EMPTY_LIST;
    protected BaseClass nextInChain;
    protected abstract void doMethod();  // your doA, doB methods

    public void execute(String input) {
            // this replace many ifs in your previous implementation
        if (patterns.contains(input)) {
            doMethod();
        } else {
            nextInChain.execute(input);
        }       
    }

    public void setPatterns(Collection<String> patterns) {
        this.patterns = patterns;
    }

    public void setNextInChain(BaseClass nextInChain) {
        this.nextInChain = nextInChain;
    }
}

Class in chain:

public class ClassA extends BaseClass {
    ClassA(Collection<String> patterns) {
        setPatterns(patterns);
    }
    @Override
    protected void doMethod() {
        // do A     
    }
}

public class ClassB extends BaseClass {...}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文