Does the class below implement the singleton pattern? I'm really confused.
class Customer {
static private Map costumers = new HashMap();
private Customer() {
}
public static Customer getInstance(String name) {
Customer instance = (Customer) costumers.get(name);
if (instance == null) {
instance = new Customer();
costumers.put(name, instance);
}
return instance;
}
}
Thanks.
No, it doesn't. Thread-safety and type-safety issues aside, I can very easily get two different instances of Customer
:
Customer x = Customer.getInstance("first");
Customer y = Customer.getInstance("second");
System.out.println(x == y); // false
Therefore it's not a singleton. It's a sort of factory/flyweight pattern hybrid, but it's certainly not the singleton pattern.
See more on this question at Stackoverflow