Java设计模式——单例设计模式

1.单例设计模式的定义

定义:保证一个类只有一个实例,并且提供一个访问它的全局访问点


2.单力设计模式的特点

特点:

a.构造方法私有化

注:保证本类外部不能实例化对象

b.在类中声明一个私有静态对象

注:对象是静态的,保证了全局使用

c.给外部提供一个静态方法获取对象实例

注:方法是静态的,因为本类外部要获取这个私有静态对象实例必须通过 类名.静态方法() 的形式获取这个对象


3.单力设计模式的适用范围

a.类中没有属性,只有方法

b.工具类(频繁使用,避免多次创建对象,造成浪费内存)


4.单例设计模式的分类

a.饿汉式:很急,对象的声明和创建一起完成

b.懒汉式:对象先声明,要用到对象时再创建


5.代码示例

a.饿汉式

//饿汉式
class SingleInstance
{
	private static SingleInstance singleInstance = new SingleInstance();
	private SingleInstance(){}
	public static SingleInstance getSingleInstance()
	{
		return singleInstance;
	}
	public void method()
	{
		System.out.println("method");
	}
}

public class SingleInstanceTest
{
	public static void main(String[] args)
	{
		SingleInstance s = SingleInstance.getSingleInstance();
		s.method();
	}
}

b.懒汉式

//懒汉式
class SingleInstance
{
	private static SingleInstance singleInstance = null;
	private SingleInstance(){}
	public static SingleInstance getSingleInstance()
	{
		if(singleInstance == null)
		{
			singleInstance = new SingleInstance();
		}
		return singleInstance;
	}
	public void method()
	{
		System.out.println("method");
	}
}

public class SingleInstanceTest
{
	public static void main(String[] args)
	{
		SingleInstance s = SingleInstance.getSingleInstance();
		s.method();
	}
}






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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值