标签:mon 懒汉式 code 很多 rgs rri 特点 代码 struct
一、名词解释
私有的构造方法;
指向自己实例的私有静态引用;
以自己实例为返回值的静态的公有方法。
package com.example.demo.dataStructure.designPatten.singleTon; /** * 单例模式-懒汉式 */ public class SingletonDemo1 { private static SingletonDemo1 instance = null; private SingletonDemo1() {} public static SingletonDemo1 getInstance() { // 真正用到的时候在实例化 if(instance == null) { instance = new SingletonDemo1(); } return instance; } }
package com.example.demo.dataStructure.designPatten.singleTon; /** * 单例模式-饿汉式 */ public class SingletonDemo2 { private static SingletonDemo2 instance = new SingletonDemo2(); // 类加载的时候实例化 private SingletonDemo2() {} public static SingletonDemo2 getInstance() { return instance; } }
package com.example.demo.dataStructure.designPatten.singleTon; public class Test { public static void main(String[] args) { // 起10个线程 for (int i = 0; i < 10; i++) { new TestThread().start();; } } } class TestThread extends Thread { @Override public void run() { int hash = SingletonDemo1.getInstance().hashCode();// 更换类名来获取不同的实例 System.out.println(hash); } }
1 package com.example.demo.dataStructure.designPatten.singleTon; 2 3 /** 4 * 双重检验懒汉式 5 * */ 6 public class SingletonDemo3 { 7 private static volatile SingletonDemo3 instance = null; // volatile 关键字作用 8 9 private SingletonDemo3() {} 10 11 public static SingletonDemo3 getInstance() { 12 if(instance == null) { 13 synchronized (SingletonDemo3.class) { 14 if(instance == null) { 15 instance = new SingletonDemo3(); 16 } 17 } 18 } 19 return instance; 20 } 21 22 }
二、静态内部类
1 package com.example.demo.dataStructure.designPatten.singleTon; 2 3 public class SingletonDemo4 { 4 private SingletonDemo4() {} 5 6 private static class CreInstance { 7 private static SingletonDemo4 instance = new SingletonDemo4(); 8 } 9 10 public static SingletonDemo4 getInstance() { 11 return CreInstance.instance; 12 } 13 }
package com.example.demo.dataStructure.designPatten.singleTon; public enum SingletonDemo5 { INSTANCE; }
标签:mon 懒汉式 code 很多 rgs rri 特点 代码 struct
原文地址:https://www.cnblogs.com/xiaobaobei/p/9638157.html