Java单例模式下私有变量仅自增一次的原理咨询
Hey there! Let's break down exactly why your a variable only increments once even though you're triggering instance retrieval three times. It all boils down to how Java Singleton Pattern works and the core rules of class vs instance-level members.
核心逻辑:单例的"唯一实例"保证
First off, the entire purpose of a singleton is to ensure only one instance of the class exists throughout your application. Here's how your code enforces that:
- The constructor
private ClassicSingleton()is markedprivate—this means no external code can directly callnew ClassicSingleton()to create a new object. - The static variable
private static ClassicSingleton instance = nullbelongs to theClassicSingletonclass itself (not any specific object instance). Once this variable is assigned an instance, it stays that way for the class's lifetime.
执行流程一步步拆解
Let's walk through what happens each time you call the singleton's getInstance() method (I'm assuming it's the standard lazy-loaded implementation):
- First call:
instanceisnull, so the code creates a new instance vianew ClassicSingleton(). This triggers the private constructor, wherea++runs (turningafrom 0 to 1) and your print statements execute. - Second & third calls:
instanceis already pointing to the existing object. The code skips creating a new instance and just returns the one that was already made. The constructor never gets called again—soa++never runs those extra times.
额外澄清:实例变量 vs 静态变量
Just to clear up the difference between your a and b variables:
private int a = 0is an instance variable: Each new object gets its own copy. But since we only ever create one singleton instance,ais initialized once and modified once.static int b = 0is a class variable: There's only one copy shared across all instances (even if no instances exist). If you had putb++in the constructor, it would also only run once here—same reason, constructor only executes once.
快速验证方法
If you add a print statement in your getInstance() method that outputs the instance's hash code, you'll see all three calls return the exact same object. That's the singleton guarantee in action!
内容的提问来源于stack exchange,提问作者Kad

