|
I'm writing a card game, and I made a class for the current status of the game. A lot of different components need to access the gamestatus, and work with it. Now I don't want every component to have their own private object variables because then I'd have to change them all if the game status changes. So I want each object to access the main status so I just want each object to have some kind of reference to the main variable.
Put into a simple example, I'd like this to output "foobar"
public class Main {
static String hier;
public static void main(String[] args) {
text = "foo";
myString i = new myString(text);
System.out.println(i.get()); // output foo
hier = hier + "bar";
System.out.println(i.get()); // still outputs foo
}
}
class myString
{
public String s;
public myString(String st)
{
s = st;
}
public String get()
{
return s;
}
}
Thanks for your help!
|
|
|
Use what's called a singleton (It's one of the major Design Patterns). It would look something like this.
public class Main {
static String hier;
public static void main(String[] args) {
text = "foo";
myString i = myString.init(text);
System.out.println(i.get()); // output foo
hier = hier + "bar";
System.out.println(i.get()); // still outputs foo
}
}
public class myString
{
private String s;
private static myString myStringInstance;
private myString(String st)
{
s = st;
}
public static myString init(String st)
{
myStringInstance = new myString(st);
return myStringInstance;
}
public static myString getInstance()
{
return myStringInstance;
}
public static String get()
{
return s;
}
}
semper fi...
|
|
|
I've read about those Singletons, but I don't see how they can help me out in the current situation. Could you please tell me some more about that?
Thanks, Ciro.
|
|
|
|
|
|
|
|