创建单例模式两种方式

* 什么是单例模式:
* 单:唯一
* 例:实例
* 单例设计模式,即某个类在整个系统中只能有一个实例对象可以获取和使用的代码模式
*
* 设计要点:
* 一、一个类只能有一个实例:
* 构造器私有化
* 二、它必须自行创建这个实例:
* 含有一个该类的静态变量来保存这个唯一的实例
* 三、它必须自行向整个系统提供这个实例
* 对外获取该实例对象的方式:
* 1、直接暴露 2、使用静态变量的get来获取* 常见的两种形式:饿汉式、懒汉式

一、饿汉模式

一、第一种方式

public class Singleton1 {
    public static final Singleton1 INSTANCE = new Singleton1(); private Singleton1(){ } } 

二、第二种方式

使用枚举的方式创建,是饿汉模式里面最简单的一种

public enum  Singleton2 {
    INSTANCE } 

三、第三种方式

使用场景:适合复杂初实例化

public class Singleton3(){
  private static final Singleton INSTANCE; static { INSTANCE= new Singleton3(); } private Singleton3(){ } }

使用:加载src下面一个properties文件里面的初始值

package com.example.springboot.test;

import java.io.IOException;
import java.util.Properties;

/**
 * @Author chenduoduo * @create 2020/4/15 10:49 * 静态代码块的饿汉式 * 使用的场景:符合复杂实例化 */ public class Singleton3 { public static final Singleton3 INSTANCE; private String info; static { try { //加载properties文件 Properties pro =new Properties(); //使用类加载器加载,可以避免线程安全问题 pro.load(Singleton3.class.getClassLoader().getResourceAsStream("singleton.properties")); INSTANCE = new Singleton3(pro.getProperty("info")); } catch (IOException e) { throw new RuntimeException(e); } } private Singleton3(String info){ this.info = info; } @Override public String toString() { return "Singleton3{" + "info='" + info + '\'' + '}'; } } 

获取值

public class SingletonTest {
    public static void main(String[] args) { Singleton3 instance = Singleton3.INSTANCE; System.out.println(instance); } }

二、懒汉模式

一、第一种方式

* 1、构造器私有化
* 2、使用静态变量来保存唯一实例
* 3、提供一个静态方法,获取这个对象
*    适合单线程:多线程下不安全
 public static Singleton4 getInstance(){ if(instance == null){ instance = new Singleton4(); } return instance; }

二、第二种方式

public class Singleton5 {

    private static Singleton5 instance; private Singleton5(){ } public static Singleton5 getInstance(){ if(instance == null){ //后面如果new过的话,就先判断一下 synchronized (Singleton5.class){//同步 try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } if(instance == null){ instance = new Singleton5(); } } } return instance; } }

三、第三种方式

静态内部类的方式,不存在线程安全问题

public class Singleton4{
 
  private Singleton4(){ } private class inner{ private static final Singleton4 INSTANCE = new Singleton4(); } public static singleton4 getinstance(){ return inner.INSTANCE } }

 推荐:上海vi设计

猜你喜欢

转载自www.cnblogs.com/1994july/p/12709339.html