Java如门:单例设计模式

单例设计模式的作用:让一个类只能创建一个实例(因为频繁的创建对象,回收对象会造成系统性能下降。)。解决对象的唯一性,保证了内存中一个对象是唯一的 。
 1、私有化所有的构造方法 不让外部自己去创建
 2、给外部提供一个静态方法 获取当前类的一个对象
 3、必须定义一个静态变量来保存当前类唯一的一个对象
 4、创建对象
  饿汉式:在定义静态成员变量时 直接创建当前类的一个对象 进行赋值

 private  static  HttpOpreation instance = new HttpOpreation();

  懒汉式:默认不创建,当调用时才创建。

public static  HttpOpreation getInstance(){
//判断对象是否有值
        if (instance==null){
//加锁
            synchronized (HttpOpreation.class) {
                if (instance == null){
//创建一个对象
                    instance = new HttpOpreation();
                }
            }
        }
        return  instance;

 整个代码浏览
 HttpOpreation类

public class HttpOpreation {
   // private  static  HttpOpreation instance = new HttpOpreation();
    private static HttpOpreation instance;
    public HttpOpreation() {
    }
    public static  HttpOpreation getInstance(){
        if (instance==null){
            synchronized (HttpOpreation.class) {
                if (instance == null){
                    instance = new HttpOpreation();
                }
            }
        }
        return  instance;
    }

}

 Myclass类

public class Myclass {
    public static void main(String[] args) {
        HttpOpreation httpOpreation = HttpOpreation.getInstance();
        HttpOpreation httpOpreation1 = HttpOpreation.getInstance();
        System.out.println(httpOpreation);
        System.out.println(httpOpreation1);
    }
}

 执行结果


image.png

你可能感兴趣的:(Java如门:单例设计模式)