知识总结:
概念:
要求:
方式:
饿汉式:(空间换时间)
SingletonHungry.java文件:
package com.imooc.singleton;
/*饿汉式,创建对象实例的时候直接类型实例化*/
public class SingletonHungry {
//1.创建类中的私有构造
private SingletonHungry(){
}
//2.创建该类型的私有静态实例
private static SingletonHungry instance=new SingletonHungry();
/*3.创建共公有静态方法,返回静态实例对象
*对于普通方法而言,不需要在方法前加复合数据类型,例如类名
*但是该方法返回的是一个对象,该对象属于类,所以要加上
*类名SingletonHungry
*/
public static SingletonHungry getInstance()
{
return instance;
}
}
package singleTest;
import com.imooc.singleton.SingletonHungry;
public class SingeltonHungry_Test {
public static void main(String[] args){
/*由于构造方法定义为private,所以在创建测试类中可以声明对象,但是创建实例化新对象是不允许的,
* 声明的对象必须通过父类提供的静态方法调用已经实例化的对象,
* 新创建对象会首先去找父类的无参构造方法,但是无参构造方法已经被定义为private所以禁止访问
* SingletonHungry one=new SingletonHungry();造成编译错误
*/
//调用父类的静态方法,用静态访问方式,类名.方法
SingletonHungry one=SingletonHungry.getInstance();
SingletonHungry two=SingletonHungry.getInstance();
System.out.println(one==two);//是否指向同一空间
System.out.println(one);
System.out.println(two);
}
}
测试结果:
优点缺点:
懒汉式:(时间换空间)
SingletonLazy.java文件:
package com.imooc.singleton;
/*懒汉式,类内实例对象并不初始化,直到第一次调用get方法时候才完成初始化操作*/
public class SingletonLazy {
//1.创建私有构造方法
private SingletonLazy(){
}
//2.创建静态的该类实例对象
private static SingletonLazy instance=null;
//3.创建开放的静态方法提供实例对象
public static SingletonLazy getInstance(){
if(instance==null)
{
instance=new SingletonLazy ();
}
return instance;
}
}
SingletonLazy_Test文件:
package singleTest;
import com.imooc.singleton.SingletonLazy;
public class SingeltonHungry_Test {
public static void main(String[] args){
/*由于构造方法定义为private,所以在创建测试类中可以声明对象,但是创建实例化新对象是不允许的,
* 声明的对象必须通过父类提供的静态方法调用已经实例化的对象,
* 新创建对象会首先去找父类的无参构造方法,但是无参构造方法已经被定义为private所以禁止访问
* SingletonHungry one=new SingletonHungry();造成编译错误
*/
//调用父类的静态方法,用静态访问方式,类名.方法
SingletonLazy one=SingletonLazy.getInstance();
SingletonLazy two=SingletonLazy.getInstance();
System.out.println(one==two);//是否指向同一空间
System.out.println(one);
System.out.println(two);
}
}
执行情况:
饿汉式 pk 懒汉式:
什么场合更适合用单例设计?