Java寒假学习Day18:单例模式及其实现的两种方法

1.什么是单例模式?实现的思路?

 2.具体实现

2.1饿汉式实现

/*
 * 
 * 单例模式1:饿汉式
 */
public class Singleton1 {
	public static void main(String[] args) {
		Test1 t1 = Test1.getTest1();
		Test1 t2 = Test1.getTest1();
		
		System.out.println(t1 == t2);
	}
}

class Test1{
	
	//1.私有化构造器
	private Test1() {
		
	}
	//2.在类内部创建类对象
	//4.把创建的对象也设置为静态的
	private static Test1 test1 = new Test1();
	
	//3.返回类对象,
	//由于构造器私有,没办法在外部调用返回方法,故要求其为静态,随类的加载而加载
	public static Test1 getTest1() {
		return test1;
	}
}

2.2懒汉式实现


/*
 * 
 * 单利设计模式
 * 2.懒汉式
 */
public class Singleton2 {
	public static void main(String[] args) {
		Test2 t1 = Test2.getTest2();
		Test2 t2 = Test2.getTest2();
		
		System.out.println(t1 == t2);
	}
}

class Test2{
	
	//1.私有化构造器
	private Test2() {
		
	}
	
	//2.在类内部创建类的对象
	//4.设置类对象为静态
	//	由于对象中要调用test2 所以test2也需要定义为static的
	private static Test2 test2 = null;
	
	//3.返回设置的对象
	//由于外部无法创建类的对象,
	//	调用getTest2()方法,所以要求其为静态方法,随类的加载而加载
	public static Test2 getTest2() {
		if(test2 == null)
		test2 = new Test2();
		return test2;
	}
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值