- 私有化构造器
- 内部声明静态对象
- 提供获取对象的方法
一、饿汉式单例模式
缺点: 类加载时就创建对象,加载时间过长
优点: 天然就是线程安全的
/*** 单例模式--饿汉式*/public class Dog {// 静态属性 随着类加载而加载private static Dog dog = new Dog();// 构造器设为私有 禁止外部创建对象private Dog() {}/*** 将唯一的对象返回* @return*/public static Dog getDog() {return dog;}}
二、懒汉式单例模式
缺点: 线程不安全
优点: 使用时在创建对象
/*** 单例模式--懒汉式*/public class Dog {// 静态属性 随着类加载而加载private static Dog dog = null;// 构造器设为私有 禁止外部创建对象private Dog() {}/*** 将唯一的对象返回* @return*/public static Dog getDog() {if (dog == null) {dog = new Dog();}return dog;}}
三、线程安全的懒汉式单例模式
/*** 创建人:LYY* 创建时间:2022/4/27* 懒汉式单实例* 线程安全的* 同步方法实现线程安全的*/public class Dog {// 全局静态变量private static Dog dog = null;//私有化构造器private Dog() {}/*** 同步方法实现线程安全* @return*/public static synchronized Dog getDog() {if (dog == null) {dog = new Dog();}return dog;}}
/*** 创建人:LYY* 创建时间:2022/4/27* 懒汉式单实例* 线程安全的* 同步代码块实现线程安全的*/public class Dog {// 全局静态变量private static Dog dog = null;//私有化构造器private Dog() {}/*** 同步代码块实现线程安全* @return*/public static synchronized Dog getDog() {// 效率更好if (dog == null) {// 同步代码块synchronized (Dog.class) {if (dog == null) {dog = new Dog();}}}return dog;}}
