设计模式---单例模式

1>单例类

package com.demo.singleton;

public class SingletonTest {
	public static int num=0;//用于记录该类被实例化的次数
	//声明一个类变量,外部代码想要得到SingletonTest对象,则返回该对象
	private static SingletonTest st =null;
	//将构造函数声明为private ,防止在外部代码直接new SingletonTest对象
	private SingletonTest(){
		num++;
		System.out.println("SingletonTest()---"+num);
	}
	
	//得到SingletonTest类对象的方法
	/*
	 *由于该类的构造方法声明为private的,所以不能在外部代码直接new一个该类的对象,
	 *所以也就不能调用实例方法,所以将getInsetance()方法声明为实例方法也就没有意义了,
	 *因为没有实例对象的话,也就不能调用该对象的实例方法。
	 *也是因为不能在外部直接new该类的对象,所以,外部能够访问该的方法只有类方法与类变量了,
	 *所以要将getInstance方法声明为类方法,也即static方法。
	 */
	public static SingletonTest getInstance (){
		
		if(st==null){//当st对象不空时,创建一个
			st=new SingletonTest();
		}
		System.out.println("getInstance ()----"+num);
		return st;
	}
}

2>测试类

package com.demo.singleton;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		SingletonTest st=null;
		for(int i=0;i<10;i++){
			System.out.println("index :"+i);
			st=SingletonTest.getInstance();			
		}
	}

}


输出:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值