* シングルトンパターンとは: * シングル:のみ * 例:インスタンス * シングルトンデザインパターン、つまり、システム全体で1つのインスタンスオブジェクトのみがクラスを取得および使用できるコードパターン * * デザインポイント: * 1。クラスはインスタンスを1つだけ持つことができます: * コンストラクターのプライベート化 * 2番目に、このインスタンスを自分で作成する必要があります: * この一意のインスタンスを保存するこのクラスの静的変数を含みます * 3番目に、このインスタンスをシステム全体に提供する必要があります * インスタンスオブジェクトを外部から取得する方法: * 1 、直接露出2 、静的変数get を使用して* 共通の2つの形式を取得します。空腹の中国スタイル、遅延スタイル
1.空腹モード
1.最初の方法
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の下のプロパティファイルに初期値を読み込む
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); } }
2、遅延モード
1.最初の方法
* 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デザイン