如何有一个通用的方法来对用户对象的两个不同实例执行相同的操作



以下是我正在处理的代码当前的样子:

Class A {
boolean someVariable;
String  anotherVariable;
//getters and setters
}
Class B {
boolean someVariable;
String  anotherVariable;
//getters and setters
}
Class LetsSayMainClass {
//init instances for A and B class
performThis(a);
performThis(b);
private boolean performThis(Object obj) {
if (obj instanceof A)
//assign a variable with the value of obj type casting to A
else if (obj instanceof B)
//assign a variable with the value of obj type casting to B
if (obj.getSomeVariable)
//Do Something
if (obj.anotherVariable.isEmpty())
//Do Something
}
}

AB有一些共同的变量和方法,我想对它们执行一些检查。我无法更改这些类以拥有一个通用的可实现接口和工厂来更好地实例化。因此,在这一点上,由于要进行的检查对这两个类都是常见的,所以我尝试在performThis方法中使用一个实例来避免代码重复。

我不能在performThis方法中做这样的事情

private boolean performThis(Object obj) {
if (obj instanceof A)
obj = (A) obj;
else if (obj instanceof B)
obj = (B) obj;
if (obj.getSomeVariable)
//Do Something
if (obj.anotherVariable.isEmpty())
//Do Something
}

使用变量的if条件将抛出错误,因为它们仍然将obj视为Object的实例,而不是AB的实例。

我可以用两种不同的方法来处理这个问题。但是,有没有办法避免代码重复?我可以在现有设置中使用什么?

我可能不会这么做,但如果你坚持不重复,你可以做的一件事就是作为代理加入类型。

class AorB {
A a;
B b;
public AorB(Object o) {
if (o instanceof A) {
a = (A) o;
} else if (o instanceof B) {
b = (B) o;
} else {
// throw something?
}
}
public boolean getSomeVariable() {
return isA()
? a.someVariable
: b.someVariable;
}
public String getAnotherVariable() {
return isA()
? a.anotherVariable
: b.anotherVariable;
}
public boolean isA() {
return b == null;
}
// rest
} 

这将允许您这样定义performThis

private boolean performThis(Object obj) {
AorB aOrB = new AorB(obj);      
if (aOrB.getSomeVariable())
System.out.println(aOrB.getAnotherVariable());
if (!aOrB.getAnotherVariable().isEmpty())
System.out.println(aOrB.getAnotherVariable());
return aOrB.isA();
}  

并像这样使用:

class Main {
public static void main(String[] args) {
A a = new A();
a.someVariable = true;
a.anotherVariable = "This is an A";
B b = new B();
b.someVariable = true;
b.anotherVariable = "This is a B";
LetsSayMainClass lsmc = new LetsSayMainClass();
lsmc.performThis(a); // prints "This is an A" 2x
lsmc.performThis(b); // prints "This is a B" 2x
}
}

最新更新