Chinaunix首页 | 论坛 | 博客
  • 博客访问: 580542
  • 博文数量: 748
  • 博客积分: 5000
  • 博客等级: 大校
  • 技术积分: 5005
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-08 12:36
文章分类

全部博文(748)

文章存档

2011年(1)

2008年(747)

我的朋友

分类:

2008-09-08 18:17:12

Singleton模式主要作用是保证在中,一个Class只有一个实例存在。
    一般有三种方法:
    1 定义一个类,它的构造函数为private的,所有方法为static的。如java.lang.Math
      其他类对它的引用全部是通过类名直接引用。例如:
      public final class Math {
      
      
      private Math() {}
      
      public static int round(float a) {
        return (int)floor(a + 0.5f);
      }
      ...
      }
        
    2 定义一个类,它的构造函数为private的,它有一个static的private的该类变量,在类初始化时
      实例话,通过一个public的getInstance方法获取对它的引用,继而调用其中的方法。例如:
      public class Runtime {
          
          private static Runtime currentRuntime = new Runtime();      
          
          public static Runtime getRuntime() {
            return currentRuntime;
          }
          ...
         
    3 定义一个类,它的构造函数为private的,它有一个static的private的boolean变量,用于表示
      是否有实例存在。例如:        
      
      class PrintSpooler
      {
        //this is a prototype for a printer-spooler class
        //such that only one instance can ever exist
        static boolean
            instance_flag=false; //true if 1 instance
        public PrintSpooler() throws SingletonException
        {
            if (instance_flag)
                throw new SingletonException("Only one spooler allowed");
            else
                instance_flag = true; //set flag for 1 instance
            System.out.println("spooler opened");
        }
        //-------------------------------------------
        public void finalize()
        {
        instance_flag = false; //clear if destroyed
        }
    }



--------------------next---------------------

阅读(384) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~