单例模式,其实就是对于一个类,只能新建一个对象,不能有多个重复的对象。这样使得在程序在运行时,比如日志加载时能找到唯一的对象,以至正确匹配。就类似于一山不能有二虎一样。主要的思想其实就是运用static,在类内部new一个自己的对象,再通过类方法返回这个对象。由于静态方法new出的对象,故其实有着同样的hashCode,也即同一个对象。一下是代码:
一、测试类(Test.java)
package com.demo_type;
public class Test {
public static void main(String[] args){
//饿汗模式
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
if(s1 == s2){
System.out.println("s1 = s2");
}
else{
System.out.println("s1 != s2");
}
//懒汉模式
Singleton2 s3 = Singleton2.getInstance();
Singleton2 s4 = Singleton2.getInstance();
if(s3 == s4){
System.out.println("s3 and s4 is the same");
}
else{
System.out.println("s3 and s4 is NOT the same");
}
}
}
2.Singleton.java(饿汉模式)
package com.demo_type;
/**
* @author YBnew
* 单例模式Singleton
* 应用场合:有些对象只需要一个就足够了,如皇帝
* 作用: 保证整个应用程序中某个实例有且只有一个
*/
public class Singleton {
//1.将构造方法私有化,不允许外部直接创建对象
private Singleton(){
}
//2.自己创建一个类的唯一实例
//3.将其便为static(如果将其设为private,更符合封装)
private static Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
}
3.Singleton2.java(懒汉模式)
package com.demo_type;
/**
* @author YBnew
* 懒汉模式
* 区别: 饿汉模式的特点是加载类时比较慢,但运行是比较快-线程安全
* 懒汉模式的特点是加载类时比较快,但运行时比较慢-线程不安全
*/
public class Singleton2 {
//1.将构造函数私有化,不允许外部直接创建对象
private Singleton2(){
}
//2.声明类的唯一实例,使用private static 修饰
private static Singleton2 instance;
//3.判断一下,也即运行时加载
public static Singleton2 getInstance(){
// if(instance == null){
// return new Singleton2();
// }
// else{
// return instance;
// }
if(instance == null){
instance = new Singleton2();
}
return instance;
}
}
懒汉模式和饿汉模式的取名也比较容易理解,因为懒汉模式在类加载时就已经new出了对象,这种模式new对象很着急,
而懒汉就你需要的时候再new,不紧不慢的。
注:new的快慢,饿汗在加载类时,就new好了对象。放在内存中,在调用静态方法时,得到new的对象。而懒汉则是在真正需要对象时,才new出对象。