1、设计模式概述
1、设计模式是软件开发人员在软件开发过程中面临的一般问题的解决方案。
2、23中设计模式分为创建型模式,结构型模式和行为型模式。
2、单例模式的定义和作用
1、目的:使得类的一个对象成为该系统中的唯一实例
2、定义:一个类有且仅有一个实例,并且自行实例化向整个系统提供。
3、要点:(1)某个类只能有一个实例,(2)必须自行创建实例,(3)必须自行向整个系统提供整个实例
4、实现:(1)只提供私有的构造方法,(2)含有一个该类的静态私有对象。(3)提供一个静态的公有方法用于创建和获取静态的私有对象
5、代码实现方案:(1)饿汉式:类中私有对象创建过程中即可实例化,(2)懒汉式:静态公有方法找那个实例化
3、饿汉式的代码实现
1、下面的代码展示了最简单的额汉式的代码实现
package com.imooc.singletonProj;
public class Singletonone {
//1、提供类中私有构造
private Singletonone() {
}
//2、创建该类型的私有静态实例
private static Singletonone instance=new Singletonone();
//3、创建公有静态方法返回静态实例对象
public static Singletonone getInstance() {
return instance;
}
}
然后我们测试一下这个类是不只能实例化出一个对象?
package com.imooc.singletontest;
import com.imooc.singletonProj.Singletonone;
public class Singletononetestdemo {
public static void main(String[] args) {
Singletonone one=Singletonone.getInstance();
Singletonone two=Singletonone.getInstance();
System.out.println(one);
System.out.println(two);
System.out.println(one==two);
}
}
看看测试结果:
com.imooc.singletonProj.Singletonone@7852e922
com.imooc.singletonProj.Singletonone@7852e922
true
很明显,使用公有的静态方法去获取类的唯一实例,不管使用这个类创建多少个实例,虽然实例名称不同,但是指的都是同一段堆中的内存,也可以使用equals方法去实践一下,这里就不展示了。
2、饿汉式的代码有很明显的特点:速度快,空间大,周期长。管你用不用我这个类,我先把实例创建出来。
4、懒汉式的代码实现
1、下面的代码展示了最简单的懒汉式的代码实现
package com.imooc.singletonProj;
public class Singletontwo {
//1创建私有的构造方法
private Singletontwo() {
}
//2创建静态的该类实例对象
private static Singletontwo instance=null;
//3创建开放的静态方法提供实例对象
public static Singletontwo getInstance() {
if(instance==null)
instance=new Singletontwo();
return instance;
}
}
测试代码如下:
package com.imooc.singletontest;
import com.imooc.singletonProj.Singletonone;
import com.imooc.singletonProj.Singletontwo;
public class Singletononetestdemo {
public static void main(String[] args) {
Singletontwo one=Singletontwo.getInstance();
Singletontwo two=Singletontwo.getInstance();
Singletonone haha=Singletonone.getInstance();
Singletonone heihei=Singletonone.getInstance();
System.out.println(one);
System.out.println(two);
System.out.println(one.equals(two));
System.out.println(haha);
System.out.println(heihei);
System.out.println(haha.equals(heihei));
}
}
测试结果:
com.imooc.singletonProj.Singletontwo@7852e922
com.imooc.singletonProj.Singletontwo@7852e922
true
com.imooc.singletonProj.Singletonone@4e25154f
com.imooc.singletonProj.Singletonone@4e25154f
true
5、饿汉懒汉的比较:
1、饿汉式损耗的是空间,节省的是时间,懒汉式损耗的是时间,节省的是空间
2、饿汉式线程安全,懒汉式存在线程风险。所以后面我们会说通过同步锁,双重检验锁,静态内部类和枚举的方式保证实例唯一。