Java Singleton Pattern: Enum, Lazy Holder & Double-Checked Locking Explained
Maya's bookstore app has grown since the last post. Checkout, receipts, and nightly reports all need the same shop settings: the store name, the currency, and the tax rate. Each part of the app loads those settings its own way — checkout reads the settings file when it starts, receipts read it again when printing, reports read it a third time overnight. That worked until the day Maya changed the tax rate at noon: checkout used the new rate, receipts still used the old one, and the day's books did not reconcile. Three copies of "the settings" turned out to be three chances to disagree. This post is about the pattern that answers a different question from the last one. Post 1, Design Patterns in Java: What They Are, When to Use Them, and When Not To , asked what varies? This post asks how many? — and when the honest answer is "exactly one," the Singleton pattern is the shape for it. The principle for this lesson: a singleton answers "how many?" —...