Reputation: 136
I recently read about the singleton principle but I dont quite get how I can initialize this single instance of a class form another class if the constructor is private
. And how do I set parameters from another class if the constructor is supposed to be private
?
public class Player {
String name;
Position p;
Inventory i;
private Player(String name, Position p, Inventory i){
}
static {
instance =
}
public static Player getPlayer(){
return instance;
}
}
Upvotes: 2
Views: 2359
Reputation: 14968
Basically, with this approach you hide the constructor (private
) and exposes a static method for getting the instance
. In the method you check if the instance
if null
, if so, you initialise it with the provided arguments.
Finally you return the instance
.
Notice here if you call the getPlayer
method more than once, the instance will be created (and will be the same in further calls of method getPlayer
) with the arguments provided the first time the static method was called.
public class Player {
String name;
Position p;
Inventory i;
private static Player instance;
private Player(String name, Position p, Inventory i){
// ...
}
public static Player getPlayer(String name, Position p, Inventory i){
if (instance == null) {
instance = new Player(name, p, i);
}
return instance;
}
}
Additionally, if you want to use the singleton pattern properly, you should not set the attributes (no setters methods) once the instance is created.
Upvotes: 1
Reputation: 8796
You should create a private static Player
variable, and in your getPlayer()
method or in the static block create the object and assign to the above variable if it's null.
public static Player getPlayer(){
if(player == null){
player = new Player("name", p, i);
}
return player;
}
this way you create only a single instance.
Simple rules,
private
.private static
variable.synchronized
to the getter to make it thread safe (optional).Upvotes: 3
Reputation: 3260
Just declare a private static final INSTANCE
field as
private static final INSTANCE = new Person(name, p, i);
Upvotes: 0
Reputation: 18235
In another class you call: Player.getPlayer()
It always return the only one static instance of your class. The constructor is private so other class cannot initialize your class via constructor.
The only way to obtain your Player
instance is via the static method Player.getPlayer()
hence it's singleton.
public class Player {
String name;
Position p;
Inventory i;
private static final Player instance = new Player(.....your argument....);
private Player(String name, Position p, Inventory i){
}
public static Player getPlayer(){
return instance;
}
}
Upvotes: 1