Java 如何不重复自己或如何改变方法中的简单条件?
我有一个方法,我在我的实现中多次使用它,只做了非常简单的修改。我怎样才能避免重复我自己Java 如何不重复自己或如何改变方法中的简单条件?,java,design-patterns,coding-style,dry,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.addRe
...
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的条件,例如areFriends(元素pivot,元素a),并继续使用整个代码和数据结构。我试图提取一个void方法,但在这种情况下,我必须将所有变量(db、queue等)作为输入传递,它看起来像是一个反模式。你知道如何解决这个问题吗?谢谢大家! 您可以使用命令设计模式。使用方法
public void checkElements(元素a、元素b)
创建一个接口,并创建该接口的几个实例。在方法中,使用接口的方法,或者让方法接受接口实例作为参数,或者让它作为类成员。您可以定义一个接口
:
public interface IElementFunction
{
public boolean execute(Element e1, Element e2);
}
将接口
的实现(命名或匿名类
es)传递到公共函数:
private void commonFunction(IElementFunction ief)
{
while (!queue.isEmpty()) {
Element pivot = queue.poll();
elements.remove(pivot);
for (Element a : elements) {
if (ief.execute(pivot, a)) {
db.addRelation(a, pivot);
queue.add(a);
elements.remove(a);
}
}
}
创建一个接口:
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);
}
}
}
...
}
哼。。不确定我是否完全理解您的问题,但这看起来像是实现模板方法模式或其他模式的味道 检查: