Implementing the Singleton Pattern in One Line: Scala vs. Java
The article shows that Scala’s built‑in object keyword lets you create a singleton with a single line, contrasts this with Java’s multi‑line implementation, explains why design patterns exist, and discusses when and how to use them responsibly.
The author presents a concise example of the Singleton design pattern implemented with just one line of Scala code. object Config In Scala, the object keyword is a language feature that guarantees a single instance, directly satisfying the core intent of the Singleton pattern: the entire system has only one instance.
By contrast, achieving the same effect in Java requires several lines of boilerplate code:
public class Config {
private static final Config INSTANCE = new Config();
private Config() {}
public static Config getInstance() {
return INSTANCE;
}
}The verbosity stems from Java’s language design choices. The language’s creator emphasized safety and limited programmer freedom, which reduces expressive power and forces developers to write more code to express patterns such as Singleton.
The article argues that design patterns themselves are not flawed; they are simply reusable solutions to recurring problems. For example, the Factory pattern decouples object creation from usage, the Strategy pattern enables interchangeable behavior, and the Observer pattern lets publishers ignore subscriber details.
Consequently, developers should first identify the concrete problem they need to solve before deciding whether a design pattern is appropriate.
If a global single instance is required and the project uses Java, the multi‑line implementation is the correct approach unless the language later adopts a built‑in singleton feature. In Scala, a single object declaration suffices.
Criticism of design patterns often stems from misuse: over‑engineering, Java’s inherent verbosity leading to hard‑to‑read code, and developers lacking the skill to know when a pattern is needed.
The article concludes that the pattern itself is not at fault; misuse by developers is the real issue.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
samdeepthink
Knowledge Planet: Old Dock's Tech Chronicles Zhihu: SamDeepThinking A technical manager who still codes heavily on the front line. From junior developer to tech lead, then tech manager, now leading the whole front‑ and back‑end development team—leveling up along the way. I have some insights on programming, career development, and tech management.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
