2021-04-28 16:49:39 +02:00
Singletons that aren't actually singletons become problems instead. To make sure a singleton isn't instantiable, make sure all constructors are ``++private++``. If the singleton doesn't have any constructors then add a ``++private++`` no-args constructor to override the default constructor.
This rule raises an issue when a class that holds a ``++public static final++`` instance of itself has non-``++private++`` constructors or no constructor.
2021-04-28 18:08:03 +02:00
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
----
public class Highlander implements Immortal { // Noncompliant; no constructor; default, public constructor generated
public static final Highlander INSTANCE = new Highlander();
public void eliminateRival(Immortal immortal) {
// ...
}
}
public class Kurgan implements Immortal {
public static final Kurgan INSTANCE = new Kurgan();
Kurgan() { // Noncompliant; should be private
}
public void eliminateRival(Immortal immortal) {
// ...
}
}
----
2021-04-28 18:08:03 +02:00
2021-04-28 16:49:39 +02:00
== Compliant Solution
----
public class Highlander implements Immortal {
public static final Highlander INSTANCE = new Highlander;
private Highlander() {
}
public void eliminateRival(Immortal immortal) {
// ...
}
}
public class Kurgan implements Immortal {
public static final Kurgan INSTANCE = new Kurgan;
private Kurgan() {
}
public void eliminateRival(Immortal immortal) {
// ...
}
}
----
2021-04-28 18:08:03 +02:00
2021-04-28 16:49:39 +02:00
== See
* https://wiki.sei.cmu.edu/confluence/x/_zZGBQ[CERT MSC07-J.] - Prevent multiple instantiations of singleton objects
2021-04-28 18:08:03 +02:00
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]