A pattern that guarantees that there is only one instance.
The Singleton role has a static method to get a single instance. This method always returns the same instance.
package singleton;
public class Singleton {
private static Singleton singleton = new Singleton();
//Prohibit calling the constructor from outside the class by making the constructor private
private Singleton() {
System.out.println("Created an instance");
}
//Provide a static method that returns an instance
public static Singleton getInstance() {
return singleton;
}
}
package singleton;
public class Main {
public static void main(String[] args) {
System.out.println("Start");
Singleton obj1 = Singleton.getInstance();
Singleton obj2 = Singleton.getInstance();
if (obj1 == obj2) {
System.out.println("Same instance");
} else {
System.out.println("Not the same instance");
}
System.out.println("End");
}
}
// Start
//Created an instance
//Same instance
// End
package singleton;
public class TicketMaker {
private static TicketMaker ticketMaker = new TicketMaker();
private int ticket = 1000;
private TicketMaker() {
}
public static TicketMaker getInstance() {
return ticketMaker;
}
//Grant syncronized to work properly even when called from multiple threads
public synchronized int getNextTiketNumber() {
return ticket++;
}
}
package singleton;
public class Triple {
private static Triple[] triples = new Triple[] {
new Triple(0),
new Triple(1),
new Triple(2),
};
private int id;
private Triple(int id) {
System.out.println("The instance" + id + " is created");
this.id = id;
}
public static Triple getInstance(int id) {
return triples[id];
}
public String toString() {
return "[Triple id = " + id + "]";
}
}
package singleton;
public class Main {
public static void main(String[] args) {
System.out.println("Start");
for (int i = 0; i < 9; i++) {
Triple triple = Triple.getInstance(i % 3);
System.out.println(i + ":" + triple);
}
System.out.println("End");
}
}
// Start
// The instance0 is created
// The instance1 is created
// The instance2 is created
// 0:[Triple id = 0]
// 1:[Triple id = 1]
// 2:[Triple id = 2]
// 3:[Triple id = 0]
// 4:[Triple id = 1]
// 5:[Triple id = 2]
// 6:[Triple id = 0]
// 7:[Triple id = 1]
// 8:[Triple id = 2]
// End
Recommended Posts