单例模式

一。特点:

 1.构造器私有化
2.自行创建,并用静态变量保存
3.向外提供这个实例
4.强调这是一个单例,用final修饰

一。饿汉式:在类初始化时直接创建实例对象(线程安全),不管你是否需要这个对象

  1.直接实例化饿汉式(简洁直观)

1 public class Singleton1 {
2     public static final Singleton1 INSTANCE = new Singleton1();
3     private Singleton1() { }
4 
5     public void test01(){}
6 }

  2.枚举(最简洁)

public enum Singleton2 {
    INSTANCE
}

  3.使用静态代码块(适合复杂实例化)

single.propertis:
info=zhengcj
 1 public class Singleton3 {
 2     public static final Singleton3 INSTANCE;
 3     private String info;
 4     static {
 5         try {
 6             Properties pro = new Properties();
 7             pro.load(Singleton3.class.getClassLoader().getResourceAsStream("single.propertis"));
 8             INSTANCE = new Singleton3(pro.getProperty("info"));
 9         } catch (IOException e) {
10             throw new RuntimeException(e);
11         }
12     }
13     private Singleton3(String info) {
14         this.info = info;
15     }
16     public String getInfo() {
17         return info;
18     }
19     public void setInfo(String info) {
20         this.info = info;
21     }
22 }

二。懒汉式:延迟创建对象

  1.线程不安全(适合单线程)

 1 public class Singleton4 {
 2     private static Singleton4 instance;
 3     private Singleton4() { }
 4     public static Singleton4 getInstance() {
 5         if (instance == null) {
 6             return instance = new Singleton4();
 7         }
 8         return instance;
 9     }
10 }

  2.线程安全(适合多线程)

 1 public class Singleton4 {
 2     private static Singleton4 instance;
 3     private Singleton4() { }
 4     public static Singleton4 getInstance() throws InterruptedException {
 5         if(instance == null){
 6             synchronized (Singleton4.class){
 7                 if (instance == null) {
 8                     TimeUnit.SECONDS.sleep(1);
 9                     return instance = new Singleton4();
10                 }
11             }
12         }
13         return instance;
14     }
15 }

  3.静态内部类形式(适合多线程)

  * 在内部类被加载和初始化时,才创建INSTANCE实例对象
  * 静态内部类不会自动随着外部类的加载和初始化而初始化,它是要单独去加载和初始化的。
  * 因为是在内部类加载和初始化时,创建的,因此是线程安全的
1 public class Singleton5 {
2     private Singleton5 () { }
3     private static class Inner {
4         private static final Singleton5 INSTANCE = new Singleton5();
5     }
6     public static Singleton5 getInstance(){
7         return Inner.INSTANCE;
8     }
9 }

 

posted @ 2021-01-22 13:32  真某人  阅读(95)  评论(0编辑  收藏  举报