java 单例模式

来源:互联网 发布:filter java 编辑:程序博客网 时间:2024/06/16 21:54

1.单例模式特点:

    (1)创建一个private的构造方法,确保外层不会实例化。

    (2)提供一个静态的最终的对象,该对象在类加载时被初始化,该对象是唯一一个该类的对象.

单例模式可简单分成两种:

   饿汉式和懒汉式。

  1.饿汉式

     public class  Singleton{
      //私有类对象

       private static Singleton singleton = new Singleton();

      //私有构造方法,不能让外类创建对象

      private Singleton(){

      }

      public static Singleton getInstall(){

            return singleton;

     }

   }

  饿汉式在类加载时就会创建一个对象,外面想要调用这个类,需要用getInstall方法,这个方法返回类加载时的对象。

 2.懒汉式

  public class  Singleton{
      //私有类对象

       private static Singleton singleton = null;

      //私有构造方法,不能让外类创建对象

      private Singleton(){

      }

      public synchronized static Singleton getInstall(){

            if(singleton == null){

              singleton = new Singleton();

           }

            return singleton;

     }

   }

 大家应该注意到了,饿汉式创建对象会在外面想要时再创建,如果没有会创建一个新的,这种模式多用于多线程。


下面我们用单例模式创建递增序列

 public class KeyInstall {
    private static KeyInstall key = new KeyInstall();
private int count = 0;
       private KeyInstall(){
}

public static KeyInstall getInstall(){
return key;
}

public synchronized int getSequence(){
return count++;
}
}

通过main函数验证:

public class KeyMain {
    private static KeyInstall key;
public static void main(String[] args) {
key = KeyInstall.getInstall();
System.out.println("key id :"+key.getSequence());
System.out.println("key id :"+key.getSequence());
System.out.println("key id :"+key.getSequence());
}

}

最后验证结果:

key id :0
key id :1
key id :2

0 0