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();
}
}