首页 > 其他 > 详细

单例模式 事例操作 最喜欢枚举类型单例模式

时间:2014-10-11 17:00:37      阅读:243      评论:0      收藏:0      [点我收藏+]

JAVA中单例模式是一种常见的设计模式,单例模式分五种:懒汉,恶汉,双重校验锁,枚举和静态内部类五种。
  单例模式有一下特点:
  1、单例类只能有一个实例。
  2、单例类必须自己自己创建自己的唯一实例。
  3、单例类必须给所有其他对象提供这一实例。

  单例模式确保某个类只有一个实例,而且自行实例化并向整个系统提供这个实例。在计算机系统中,线程池、缓存、日志对象、对话框、打印机、显卡的驱动程序对象常被设计成单例。这些应用都或多或少具有资源管理器的功能。每台计算机可以有若干个打印机,但只能有一个Printer Spooler,以避免两个打印作业同时输出到打印机中。每台计算机可以有若干通信端口,系统应当集中管理这些通信端口,以避免一个通信端口同时被两个请求同时调用。总之,选择单例模式就是为了避免不一致状态,避免政出多头。

下面看一下例子:有的例子是种类的变种:

package com.gd.singleton;
/**
 * 单例模式
 * @author zlm
 *
 */
public class SingletonOne {
public static void main(String[] args) {
//SingletonSix.class.newInstance();
 SingletonSix.INSTANCE.equals(SingletonSix.TEST);
 System.out.println(SingletonSix.INSTANCE.hashCode());
 System.out.println("----------------");
 System.out.println(SingletonSix.TEST.hashCode());
}
}
// 懒汉模式
class Singleton{
private static Singleton instance;
private Singleton(){
}
public static Singleton getInstance(){
    if(instance == null){
      instance =  new Singleton();
      }
      return instance;
}
}
class SingletonTwo{
private static SingletonTwo instance;
private SingletonTwo(){}
public static synchronized SingletonTwo getInstance(){
if(instance == null){
instance = new SingletonTwo();
}
return instance;
}
}
class SingletonThree{
private static SingletonThree instance = new SingletonThree();
private SingletonThree(){}
public static SingletonThree getInstance(){
return instance;
}
}
class SingletonFour{
private static SingletonFour instance = null;
static{
instance = new SingletonFour();
}
private SingletonFour(){}
public static SingletonFour getInstance(){
return instance;
}
}
class SingletonFive{
private static class SingletonHolder{
private static final SingletonFive INSTANCE = new SingletonFive();
}
private SingletonFive(){}
public static final SingletonFive getInstance(){
return SingletonHolder.INSTANCE;
}
}
enum SingletonSix{
INSTANCE,TEST;
public  void getSinglet(){
System.out.println("枚举实现单例模式!!!!!");
}
}
class SingletonSeven{
private volatile static SingletonSeven instance;
    private SingletonSeven(){}
    public static SingletonSeven getInstance(){
    if(instance == null){
    synchronized(SingletonSeven.class){
    if(instance == null){
    instance = new SingletonSeven();
    }
    }
    }
    return instance;
    }
}
//class SingletonEight{
//private static  SingletonEight instance;
//private SingletonEight(){}
//
//}


本文出自 “技术懒人” 博客,请务必保留此出处http://verify.blog.51cto.com/7460015/1562573

单例模式 事例操作 最喜欢枚举类型单例模式

原文:http://verify.blog.51cto.com/7460015/1562573

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!