Java:单例设计模式

知识总结:

概念:



要求:




方式:



饿汉式:(空间换时间)

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



SingletonHungry_Test.java文件:

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 懒汉式:




什么场合更适合用单例设计?




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值