单例模式

单例设计模式
设计模式:套路、模板
单例:是指当前工程中的某一个类的对象在内存只有一份
使用单例的目的:

  1. 节省资源
  2. 全局共享数据的统一管理

步骤:

  1. 构造函数私有化,防止其他类创建本类对象
  2. 在本类中创建本类对象
  3. 对外提供获取本类对象的方法

饿汉式

 public class Test {
	public static void main(String[] args) {
		int sum=Tools.getInstance().add(3, 4);
		System.out.println(sum);
	}
}

    class Tools{
        //1.私有化构造器
        private Tools() {}
        //2.创建本类对象
        public static Tools t= new Tools();
        //对外提供访问本类对象的方法
        public static Tools getInstance() {
            return t;
        }
        public int  add(int a, int b) {
            return a+b;
        }
}

缺点:即使没有调用getInstance方法也进行了对象的创建,浪费资源。
懒汉式

    //懒汉式
    class Tool{
        //1.私有化构造器
        private Tool() {}
        //2.1定义本类对象
        public static Tool t= null;
        //对外提供访问本类对象的方法
        public static Tool getInstance() {
            if(t==null) {
            t=new Tool();
            }
            return t;
        }
        public int  add(int a, int b) {
            return a+b;
        }
    }

缺点:不能保证线程的安全
线程安全的懒汉式

    //懒汉式
    class Tool{
        //1.私有化构造器
        private Tool() {}
        //2.1定义本类对象
        public static Tool t= null;
        //对外提供访问本类对象的方法
        public static Tool getInstance() {
            synchronized(Tool.class){
              if(t==null) {
            t=new Tool();
            }
            }
           
            return t;
        }
        public int  add(int a, int b) {
            return a+b;
        }
    }
        return t;
        }
        public int  add(int a, int b) {
            return a+b;
        }
    }

你可能感兴趣的:(单例模式)