创建全局列表对象Java

时间:2015-11-12 14:50:02

标签: java

我想创建一个可访问我的所有类的对象的全局列表。

例如,这里是创建对象的类

public class Class2 {

protected String one, two, three;

public void newItem(String one, String two, String three) {

    this.one = one;
    this.two = two;
    this.three = three;
}

public String getInfo() {

    return one + "," + two + "," + three;
}

我想从另一个类创建一个对象Class2的列表(假设为Class1.java),我希望该列表可以从另一个类中获得,比如Class3.java。

行为应该像数据库一样,其中一个类创建List,另一个类读取该列表以执行一些本地操作。

1 个答案:

答案 0 :(得分:0)

没有任何其他依赖关系和单例的简单解决方案:

//Class which represents this "data storage" of yours. You can even have multiple instances of it simultaneously if you need
class Database {
    //Some data the DB contains
    private List<MyEntity> entities = new ArrayList<>();

    //Way to read the stored data
    public List<MyEntity> getEntities() {
        return entities;
    }

    //Way to add new data
    public void addEntity(MyEntity newEntity) {
        entities.add(newEntity);
    }
}

//Some working class, which fills the database with information
class EntityCreator {
    private final Database db;

    //Each working class attaches itself to specific database instance. Therefore, you need to pass that instance through the constructor and save it for later job
    public EntityCreator(Database operationalDb) {
        this.db = operationalDb;
    }

    public void writeSomeData() {
        for (.....) {
            db.addEntity(new MyEntity(...));
        }
    }
}

//Some working class, which depends on information saved in database
class EntityReader {
    private final Database db;

    //Each working class attaches itself to specific database instance. Therefore, you need to pass that instance through the constructor and save it for later job
    public EntityCreator(Database operationalDb) {
        this.db = operationalDb;
    }

    public void doSomeWork() {
        for (MyEntity e : db.getEntities()) {
            doStuff(e);
        }
    }
}

//Example of the full workflow
class MainClass {
    public static void main(String[] args) {
        Database db = new Database();
        EntityCreator creator = new EntityCreator(db);
        EntityReader reader = new EntityReader(db);

        creator.writeSomeData();
        reader.doSomeWork();
    }
}

此外,值得注意的是,它不是线程安全的,但它提供了将连接依赖性放在一起的主要思想,而不使用DI框架。