Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

singleton - Single instance of Java class

I wanna create a single instance of a class. How can I create a single instance of a class in Java?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To create a truly single instance of your class (implying a singleton at the JVM level), you should make your class a Java enum.

public enum MyClass {
  INSTANCE;

  // Methods go here
}

The singleton pattern uses static state and as a result usually results in havoc when unit testing.

This is explained in Item 3 of Joshua Bloch's Effective Java.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...