单态设计模式

单态设计模式

Singleton模式主要作用是保证在Java应用程序中,一个类Class只有一个实例存在。

  一般Singleton模式通常有几种种形式:

第一种形式: 定义一个类,它的构造函数为private的,它有一个static的private的该类变量,在类初始化时实例话,通过一个public的getInstance方法获取对它的引用,继而调用其中的方法。

one :

package test1;

public class Singleton {

  public static Singleton instance = new Singleton() ;
  private Singleton(){}

 //这里提供了一个供外部访问本class的静态方法,可以直接访问 
  public static Singleton getInstance(){
   return instance ;
  }
  
  public static void main(String[] args) {
   Singleton S1 =  new Singleton();
   Singleton S2 =  new Singleton();
   System.out.println(Singleton.getInstance());
   System.out.println(S1);
   System.out.println(S2);
   System.out.println(S2.toString()==S1.toString());
   System.out.println(S2.equals(S1));
  }
 }
//  Runtime、Class都采用了此类形式。

 

 第二种形式:

two:

package test2;

public class Factory {

 private static Factory factory = new Factory();
 //这个方法比上面有所改进,只是第一次使用时生成实例,提高了效率
 public static Factory getFactory() {
  if (factory == null)
  factory = new Factory();
  // ...
  return factory;
  }
  
  public static void main(String[] args) {
   Factory S1 =  new Factory();
   Factory S2 =  new Factory();
   System.out.println(Factory.getFactory());
   System.out.println(S1);
   System.out.println(S2);
   System.out.println(S2==S1);
   System.out.println(S2.equals(S1));
  }
 }

 一般认为第一种形式要更加安全些
 
 three:   Singletons and Threads

package test3;

public class Factory {

 private static Factory factory;
 private static Object classLock = Factory.class;
 @SuppressWarnings("unused")
 private long wipMoves;

 private Factory() {
  wipMoves = 0;
 }

 public static Factory getFactory() {
  synchronized (classLock) {
   if (factory == null)
    factory = new Factory();
   return factory;
  }
 }

 public void recordWipMove() {
  synchronized (classLock) {
   wipMoves++;
  }
 }

 public static void main(String[] args) {
  Factory S1 = new Factory();
  Factory S2 = new Factory();
  System.out.println(Factory.getFactory());
  System.out.println(S1);
  System.out.println(S2);
  System.out.println(S2 == S1);
  System.out.println(S2.equals(S1));
 }
}

 

 典型应用

Hibernate框架中的 SessionFactory

package cn.edu.nynu.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
 private static SessionFactory sf;
 static {
  sf = new AnnotationConfiguration().configure().buildSessionFactory(); //使用Annotation生成SessionFactory的对象
 // SessionFactory     sessionFactory = new Configuration().configure() .buildSessionFactory();
 }
 
 public static SessionFactory getSessionFactory() {
  return sf;
 }
}

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值