OCM Java EE 6 Enterprise Architect Exam Guide (Exams 1Z0-807, 1Z0-865 & 1Z0-866) (Oracle Press)

Author: Paul R. Allen, Joseph J. Bambara
4.0
This Month Stack Overflow 1

Comments

by anonymous   2019-01-13

I know it is an old one but I hope I'll help others out.

Sadly the Singleton pattern has got many definitions. Examples:

Definition 1 HTDIN:

Singleton pattern is a design solution where an application wants to have one and only one instance of any class, in all possible scenarios without any exceptional condition.

Definition 2 Wikipedia:

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.

The first one is more strict but if you look at the second description is states that there could be multiple instances. This way you are able to do something like pooling.

final class Singleton {
    private static int ROUND_ROBIN_COUNTER = Integer.MAX_VALUE;
    private static final List<Singleton> INSTANCES = Arrays.asList(new Singleton(), new Singleton(), new Singleton());

    private Singleton() {}

    public static Singleton getInstance() {
        return INSTANCES.get(Math.abs((ROUND_ROBIN_COUNTER++)%INSTANCES.size()));
    }
}

According to the first definition this is not a singleton, but the second one allows that. I am reading the OCM Java EE 6 Enterprise Architect Exam Guide it also agrees with the Wikipedia definition.