singleton模式

来源:互联网 发布:巅峰阁软件下载 编辑:程序博客网 时间:2024/06/04 18:17

Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。这样的类常用来进行资源管理

分两类:饿汉式

   public class EagerSingleton{

   private EagerSingleton(){}

//构造方法为私有

   private static EagerSingleton instance=new EagerSingleton();

//在自己内部实例化

  public static  EagerSingleton getInstance(){

   return instance;

懒汉式:

public class LazySingleton{

private LazySingleton(){}

private static LazySingleton instance=null;

public static synchronized LazySingleton getInstance(){

if(instance==null){

    instance=new LazySingleton();

}

return instance;

}

 

}

 

实例:

public class PCSingleton {
 private static PC pc=new PC();

 private PCSingleton() {
 }

 public static PC create() {
  return pc;
 }
}

 

public class PC {
      public void execute(){
       System.out.println(this.hashCode());
      }
}

 

public class Test {

 public static void main(String[] args) {
     PC pc = PCSingleton.create();
     pc.execute();
     pc.execute();
 }

}
打印出的hash码完全一样

总结:

Singleton模式看起来简单,使用方法也很方便,但是真正用好,是非常不容易,需要对Java的类 线程 内存等概念有相当的了解。