java - 如何不重复自己或如何更改方法中的简单条件?

标签 java design-patterns coding-style dry

我有一个方法,我在我的实现中使用了多次,只做了非常简单的修改。我怎样才能避免重蹈覆辙?

...
    while (!queue.isEmpty()) {
        Element pivot = queue.poll();
        elements.remove(pivot);
        for (Element a : elements) {
            if (areFriends(pivot, a)) {
                db.addRelation(a, pivot);
                queue.add(a);
                elements.remove(a);
            }
        }
    }
...

我想用一个新条件更改 areFriends 条件,例如areEnemies(Element pivot, Element a) 并继续使用整个代码和数据结构。我试图提取一个 void 方法,但在这种情况下,我必须将所有变量(数据库、队列等)作为输入传递,这看起来像是一种反模式。你知道如何解决这个问题吗?谢谢!

最佳答案

创建接口(interface):

public interface Relation 
{
    public void execute(Element a, Element b);
}


public class AreFriendsRelation implements Relation 
{
    public void execute(Element a, Element b) 
    {
        // Return the Relation result
    }    
}

public class AreEnemiesRelation implements Relation 
{
    public void execute(Element a, Element b) 
    {
        // Return the Relation result
    }    
}

将您的关系对象传递给您的方法:

public void MyMethod(Relation myRelation) {
...
while (!queue.isEmpty()) {
        Element pivot = queue.poll();
        elements.remove(pivot);
        for (Element a : elements) {
            if (myRelation.execute(pivot, a)) {
                db.addRelation(a, pivot);
                queue.add(a);
                elements.remove(a);
            }
        }
    }

...
}

关于java - 如何不重复自己或如何更改方法中的简单条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15529068/

相关文章:

java - 马文 : how to filter the same resource multiple times with different property values?

java - 如何更改 JTable 中字符串的字体大小?

c# - 实现单例设计模式[请建议]

java - 为 JButton 单击的 Action Listener 类打开新窗口

java - Java 中 SOAP 和 RESTful Web 服务的主要区别

android - 管理大文件(代码行)

design-patterns - 如何用策略替换(而不仅仅是移动)条件逻辑?

c - 定义类型的顺序

java - 惯用的 Java : constraining data

c++ - 为什么 C++ 标准不弃用递增/递减运算符?