publ
提供了一种创建对象的最佳方式.
这种模式涉及到一个单一的类, 该类负责创建自己的对象, 同时确保只有单个对象被创建. 这个类提供了一种访问其唯一的对象的方式, 可以直接访问, 不需要实例化该类的对象.
意图: 保证一个类仅有一个实例, 并提供一个访问它的全局访问点.
主要解决: 一个全局使用的类频繁地创建与销毁.
何时使用: 当您想控制实例数目, 节省系统资源的时候.
- public class Singleton {
- private static Singleton instance;
- private Singleton (){}
- public static Singleton getInstance() {
- if (instance == null) {
- instance = new Singleton();
- }
- return instance;
- }
- }
- public class Singleton {
- private static Singleton instance;
- private Singleton (){}
- public static synchronized Singleton getInstance() {
- if (instance == null) {
- instance = new Singleton();
- }
- return instance;
- }
- }
- public class Singleton {
- private static Singleton instance = new Singleton();
- private Singleton (){}
- public static Singleton getInstance() {
- return instance;
- }
- }
- public class Singleton {
- private volatile static Singleton singleton;
- private Singleton (){}
- public static Singleton getSingleton() {
- if (singleton == null) {
- synchronized (Singleton.class) {
- if (singleton == null) {
- singleton = new Singleton();
- }
- }
- }
- return singleton;
- }
- }
- icclassSingleton{privatestaticSingletoninstance=newSingleton();privateSingleton(){}publicstaticSingletongetInstance(){returninstance;}}
来源: http://www.bubuko.com/infodetail-3171549.html