honeytrap.devexercisessingleton.javaSettings
Description

26. Singleton

ReadCreationalNothing to write

That one instance and a global variable are the same thing wearing different clothes

This one is for reading. Every file is locked, and Run is the only button.

This is the textbook Singleton, written the textbook way: a private constructor so nobody else can make one, a static field holding the only one there is, and a static method that hands it out. It compiles, it runs, and every assertion in Tests.java passes.

Read the last assertion. Nothing above it passed a Config to anything, and yet the read counter has gone up once for each of the two classes that ran. Two unrelated classes shared mutable state, and no signature in the program admits it: Billing’s constructor takes nothing, Reports’ constructor takes nothing, and neither of them has a field you could point at. The dependency is real, it is global, and it is invisible from every place you would look for it. That is a global variable wearing a tie.

It is a demo rather than an exercise because there is nothing here to grade. The property the pattern claims is “there is only one”, and a plain static field satisfies that too — so does a constant, so does an accident. A change request can only ask for behaviour, and this pattern’s behaviour is indistinguishable from the sloppy version of itself. The moment you write a test that tells them apart, you are testing the field, not the design.

The honest version of the lesson is the one on the front page of this site: arguments about whether the Singleton counts as a pattern are closed as wontfix. Pass the Config in. Then the signature says what the class needs, and the compiler is on your side again.

Run runs Tests.java exactly as it is written. There is nothing to edit and nothing to submit.

  • Ctrl/⌘ + Enter runs the tests