设计模式之-单例模式

单例子模式,是一种创建型模式,即在当前进程中,只有一个实例,常用来做管理资源用,主要有三种实现方式,这里只讲其中一种,主要通过例子能明白单例子模式,其它方式请读者自已实现

public class Singleton {
    private static volatile Singleton instance;	
    //防止直接通过new 出一个实例
    private Singleton(){}

    public static Singleton getInstance(){
        if(instance == null){
            synchronized (Singleton.class){
                if(instance == null){
                    instance = new Singleton();
                }
            }
        }

        return instance;
    }


    //业务方法
    public void show(){
        System.out.println("我是业务方法");
    }

}

用法 :

Singleton.getInstance().show();
说明:
Singleton
通过将构造方法限定为private避免了类在外部被实例化,在同一个虚拟机范围内,Singleton的唯一实例只能通过getInstance()方法访问。

单例的好处是在同一个进程内,随时都可以对其访问,主要用来管理一些全局性的资源。

原文地址:https://www.cnblogs.com/start1225/p/6748488.html