我想在这些对象之间共享数据。其实,例如,有一个世界由水和个人组成。 我希望个人进入水域。 我看着改变Collection中的Individual表,或者将Water变成Singleton,但是真的,最好的设计是什么? (我们可能在单个对象上有多线程进程...所以我们可能需要一个线程安全的实现。) (另外,我想知道为每个个体传递参数或实例化水,但它似乎不是最有效的实现(处理实例)...)通过对象共享数据的最佳设计是什么?
一套简单的为了解决思路对象(这一套不共享的水在所有的个人显示“空”在这里):
package myworld.testing;
public class World {
static Water evolution;
static Individual [] tribe;
public World(){
evolution=new Water();
}
public static Water getWater(){
return evolution;
}
public static void main(String[] args) {
evolution=new Water();
System.out.println("info "+evolution.get());
tribe = new Individual[10];
for(Individual individual : tribe){
System.out.println("trace "+individual);
}
evolution=new Water("sprakly");
System.out.println("info "+evolution.get());
for(Individual individual : tribe){
System.out.println("trace "+individual);
}
evolution.set("salty");
System.out.println("info "+evolution.get());
for(Individual individual : tribe){
System.out.println("trace "+individual);
}
}
}
package myworld.testing;
public class Individual {
int data;
public Individual(){
data=0;
}
public Individual(int i){
data=i;
}
public void set(int i){
data=i;
}
public int get(){
return data;
}
public String toString(){
return World.getWater().get()+" "+data;
}
}
package myworld.testing;
public class Water {
private static Water instance = null;
String type;
public static Water getInstance(){
if(instance == null) {
instance = new Water();
}
return instance;
}
public Water(){
type="1";
}
public Water(String str){
type=str;
}
public void set(String str){
type=str;
}
public String get(){
return type;
}
}
非常感谢您提前给予的帮助和建议。 随时分享您的想法:)
感谢您的回答@blackcompe。同意,并且非常真实。其目的是在'World'中实例化'Water'只有一次,并且只能从'Individual's访问这个对象。 “个人”在“世界”中被实例化。 我的疑惑是:为此目的最好的设计是什么。 我将在封装上工作。 再次感谢您的帮助。 –