2015-11-12 98 views
-2

我想創建一個全局列表,可以訪問我的包的所有類。創建全局列表對象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和其他類讀取該列表以執行一些本地操作。

+0

首先向我們展示您的最佳努力如何?檢查http://stackoverflow.com/help/how-to-ask – StarShine

+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框架一起相依的主要思想。

+0

謝謝,它的工作。 –

+0

我在我的程序上實現了這個異常發生後。我認爲你說的不是線程安全的,我想我必須研究另一個解決方案來詳細說明Java Fx應用程序線程中數據庫的數據。 –

+0

簡單的方法(可能不是非常適合您的特定場景)是用Array.synchronizedList封裝ArrayList。也就是說,在'Database'類中,將列表聲明更改爲'private List entities = Collections.synchronizedList(new ArrayList ())'。這應該使它有些線程安全。另外,這是一個快速和骯髒的解決方案,因爲正確的線程安全解決方案取決於您使用「數據庫」的特定場景。 – bezmax