单例模式

来源:互联网 发布:人工智能 学问 编辑:程序博客网 时间:2024/06/04 18:27

单例模式Singleton

1. 应用场合:有些对象只需要一个就够了,如古代的皇帝,老婆2. 作用:保证整个应用程序中某个实例有且只有一个3. 类型:饿汉模式,懒汉模式    3.1 饿汉模式:加载类时比较慢,运行时获取类对象比较快,但线程安全。    3.2 懒汉模式:加载类时比较快,运行时获取类对象比较慢,但线程不安全。

饿汉模式

public class Singleton {        //1.将构造方法私有化,不允许外部直接创建对象         private Singleton() {}         //创建类的唯一实例,使用 private static 修饰        private  static Singleton instance=new Singleton();         //提供一个获取实例的方法,用 public static 修饰        public static Singleton getInstance() {            return instance;        }}

懒汉模式

public class Singleton2 {     //1。创建一个私有的构造函数      private Singleton2() {  }      //2 声明一个实例,用private static 修饰      private static Singleton2 instance;      //3 获取实例,用public static 修饰      public static Singleton2 getInstance() {          if(instance==null) {              try {                Thread.sleep(3000);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }              instance =new Singleton2();          }          return instance;      }}

测试

public class TestSingleton {    public static void main(String[] args) {        //饿汉模式        //在类Singleton加载的时候就创建了实例。        Singleton st1=Singleton.getInstance();        Singleton st2=Singleton.getInstance();        System.out.println(st1);        System.out.println(st2);        System.out.println(st1==st2);        System.out.println(st1.equals(st2));        if(st1==st2) {            System.out.println("st1和st2是同一个实例");        }else {            System.out.println("st1和st2不是同一个实例");        }         //懒汉模式,当类gingleton2 在加载的时候并没有创建实例,而是在st3创建的时候才产生第一个实例。而后就不在创建实例了。        Singleton2 st3= Singleton2.getInstance();        Singleton2 st4 =Singleton2.getInstance();        if(st1==st2) {            System.out.println("st3和st4 是同一个实例");        }else {            System.out.println("st3和st4 不是统一个实例");        }    }}
原创粉丝点击