我有几个类,大约 40 个左右,它们实现了一个接口。我想引入一个静态变量,该变量对于该接口的每个实现类来说都是本地的。例如:
public interface MyInterface {
...
}
public class MyClass1 implements MyInterface {
public static ArrayList<String> myList;
}
public class MyClass2 implements MyInterface {
public static ArrayList<String> myList;
}
我需要每个类都有自己的静态变量版本。 有没有一种方法可以从继承的类(例如接口或抽象类)实现此目的,而不是在实现接口的所有类中重新创建相同的静态变量和方法?
我通过将静态变量和方法放入每个类中成功地实现了这一点,但我很好奇是否有一种方法可以在一个地方实现它并共享它。这个项目如此依赖于静态架构,恐怕现在尝试改变它会非常困难
您可以创建一个抽象类MyAbstract并将静态变量放入MyAbstract中。然后将 MyInterface 中的所有方法头都设为 MyAbstract 中的抽象方法。
然后让所有 40 个左右的类都扩展 MyAbstract 类,而不是实现 MyInterface。
更新:
以下是抽象父类的实现,它允许每个子类有单独的静态列表。在每个类中只需要定义其唯一的ID号并定义来自Parent的抽象方法。
import java.util.ArrayList;
abstract class Parent {
public static final int MAX_CHILDREN = 2;
private static Object[] shared = new Object[ MAX_CHILDREN ];
public void setShared(int id, Object list) {
shared[id] = list;
}
public Object getShared(int id) {
return shared[id];
}
abstract public void setShared(ArrayList<String> list);
abstract public ArrayList<String> getShared();
}
class Child1 extends Parent {
public static final int ID = 0;
public Child1( ) {
setShared(new ArrayList<String>());
}
public void setShared(ArrayList<String> list) {
setShared(ID, new ArrayList<String>());
}
public ArrayList<String> getShared() {
return (ArrayList<String>) getShared(ID);
}
}
class Child2 extends Parent {
public static final int ID = 1;
public Child2( ) {
setShared(new ArrayList<String>());
}
public void setShared(ArrayList<String> list) {
setShared(ID, new ArrayList<String>());
}
public ArrayList<String> getShared() {
return (ArrayList<String>) getShared(ID);
}
}
public class ShareStatic {
public static void main(String[] args) {
Child1 c1 = new Child1();
c1.getShared().add("Hello");
Child2 c2 = new Child2();
c2.getShared().add("Good bye");
System.out.println("C1 : " + c1.getShared().get(0));
System.out.println("C2 : " + c2.getShared().get(0));
}
}