Java中设计模式(2) Singleton模式

<script type="text/javascript"> google_ad_client = "pub-8800625213955058"; /* 336x280, 创建于 07-11-21 */ google_ad_slot = "0989131976"; google_ad_width = 336; google_ad_height = 280; // </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script> Singleton模式: Singleton模式主要作用是保证在Java应用程序中,一个Class只有一个实例存在。 一般有三种方法: 1 定义一个类,它的构造函数为private的,所有方法为static的。如java.lang.Math 其他类对它的引用全部是通过类名直接引用。例如:




          public final class Math {

          

          /**

          * Don't let anyone instantiate this class.

          */

          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

		}

	}  

        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值