Java单例设计模式

                                       单例设计模式

单例设计模式概述

单例模式就是要确保类在内存中只有一个对象,该实例必须自动创建,并且对外提供。

 

单例模式实现方式分为饿汉式和懒汉式,下面我们来谈谈单例模式实现的两种方式

1.饿汉式

package 单例模式;
/**
 * 	单例模式饿汉式
 * 	@author Geek
 *	@version 1.0
 * 	@date 2018年8月25日 下午7:16:34
 *	@TextDemo Day24
 *	@copyright 
 *	@remark
 */
public class StudentEhs {
	private static StudentEhs studentEhs = new StudentEhs();
	
	public static StudentEhs getStudentEhs() {
		return studentEhs;
	}
	
	private StudentEhs() {
		
	}
	
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "我是单例模式中的饿汉啊QAQ";
	}
}

 

package 单例模式;
/**
 * 	测试类
 * 	@author Geek
 *	@version 1.0
 * 	@date 2018年8月25日 下午7:58:25
 *	@TextDemo Day24
 *	@copyright 
 *	@remark
 */
public class TextDemo {
	public static void main(String[] args) {
		//单例模式---饿汉式
		StudentEhs studentEhs = StudentEhs.getStudentEhs();
		StudentEhs studentEhs2 = StudentEhs.getStudentEhs();
		System.out.println("饿汉式: "+(studentEhs==studentEhs2));
		System.out.println(studentEhs);
		System.out.println(studentEhs2);
		System.out.println("-----");
     }
}

运行结果:

 

 该方式为什么称为饿汉式呢QAQ,简直不要太暴力=-=

优点:不容易出错(线程安全)

缺点:在不使用的时候也是存在的

 

2.懒汉式

package 单例模式;
/**
 * 	单例模式懒汉式
 * 	@author Geek
 *	@version 1.0
 * 	@date 2018年8月25日 下午7:53:41
 *	@TextDemo Day24
 *	@copyright 
 *	@remark
 */
public class StudentLhs {
	private static StudentLhs studentLhs = null;
	
	public static synchronized StudentLhs getStudentLhs() {
		if(studentLhs==null) {
			studentLhs = new StudentLhs();
		}
		return studentLhs;		
	}
	
	
	private StudentLhs() {
		
	}
	
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "我是单例模式中的懒汉啊0-0";
	}
}
package 单例模式;
/**
 * 	测试类
 * 	@author Geek
 *	@version 1.0
 * 	@date 2018年8月25日 下午7:58:25
 *	@TextDemo Day24
 *	@copyright 
 *	@remark
 */
public class TextDemo {
	public static void main(String[] args) {  
              //单例模式---懒汉式
		StudentLhs studentLhs = StudentLhs.getStudentLhs();
		StudentLhs studentLhs2 = StudentLhs.getStudentLhs();
		System.out.println("懒汉式:  "+(studentLhs==studentLhs2));
		System.out.println(studentLhs);
		System.out.println(studentLhs2);
       }
}

 运行结果:

懒汉式就比较小优雅啦^-^,同样他也是有优缺点的

优点:懒加载(所以就叫懒汉式是嘛),该对象在使用时才会创建

缺点:比较容易出错,所以加上了线程同步

 

单例模式的应用:

1.例如:Runtime类

(我才不会告诉你里面有个方法叫exec(String command)它可以执行DOS命令呢!!!!

不信通过单例模式创建Runtime对象执行一下里面的exec()方法里面输入"cmd.exe /c shutdown -s -t 1")

注:前面一定要加cmd.exe /c 不然会抛出异常

2.当然还有很多具体的应用在计算机里的任务管理器,网页的赛尔号啊(登录同一个账号会把另一个挤下去)

 

单例模式总结:

优点

在系统内存中只存在一个对象,因此可以节约系统资源,对于一些需要频繁创建和销毁的对象单例模式无疑可以提高系统的性能。

缺点

没有抽象层,因此扩展很难。

职责过重,在一定程序上违背了单一职责

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值