在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

简单讲解在Java编程中实现设计模式中的单例模式结构

2016-7-29 15:37| 发布者: zhangjf| 查看: 626| 评论: 0

摘要: 1. 模式介绍 模式的定义 确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。 模式的使用场景 确保某个类有且只有一个对象的场景,例如创建一个对象需要消耗的资源过多,如要访问 IO 和数据库等资 ...

1. 模式介绍

模式的定义

确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。

模式的使用场景

确保某个类有且只有一个对象的场景,例如创建一个对象需要消耗的资源过多,如要访问 IO 和数据库等资源。

2. UML类图

201642293056020.png (600×189)

角色介绍:
(1)Client : 高层客户端。
(2)Singleton : 单例类。

3. 模式的简单实现

  1. public class Singleton {
  2. private static Singleton intance;
  3. private Singleton() {}
  4. public static Singleton getInstance() {
  5. /*
  6. * 一开始多线程进来,遇到锁,一个线程进去,是为空,new对象; 后续线程进入,不为空,不操作;最后直接返回
  7. * 对象不为空,再有多个线程进入该函数,不为空,不执行加锁操作,直接返回
  8. */
  9. if (intance == null) {
  10. synchronized (Singleton.class) {
  11. if (intance == null) {
  12. intance = new Singleton();
  13. }
  14. }
  15. }
  16. return intance;
  17. }
  18. }
  19. class Singleton1 {// 懒汉式
  20. private static Singleton1 intance = new Singleton1();//懒的,程序运行的时候就加载出来了
  21. private Singleton1() {}
  22. public static Singleton1 getInstance() {
  23. return intance;
  24. }
  25. }
  26. class Singleton2 {// 饿汉式
  27. private static Singleton2 intance;
  28. private Singleton2() {}
  29. public static Singleton2 getInstance() {//用到的时候 才加载
  30. if (intance == null) {
  31. intance = new Singleton2();
  32. }
  33. return intance;
  34. }
  35. }
  36. class Singleton3 {// 饿汉式 线程安全
  37. private static Singleton3 intance;
  38. private Singleton3() {}
  39. public synchronized static Singleton3 getInstance() {//用到的时候 才加载, 加锁 多线程调用,都有一个加锁的动作
  40. if (intance == null) {
  41. intance = new Singleton3();
  42. }
  43. return intance;
  44. }
  45. }
  46. class Singleton4 {// 饿汉式 线程安全
  47. private static Singleton4 intance;
  48. private Singleton4() {}
  49. public static Singleton4 getInstance() {//用到的时候 才加载
  50. synchronized (Singleton4.class) {// 加锁 效率跟3差不多
  51. if (intance == null) {
  52. intance = new Singleton4();
  53. }
  54. }
  55. return intance;
  56. }
  57. }
复制代码

4.优点与缺点

(1)优点:

A.由于单例模式在内存中只有一个实例,减少了内存开支,特别是一个对象需要频繁地创建、销毁时,而且创建或销毁时性能又无法优化,单例模式的优势就非常明显。
B.由于单例模式只生成一个实例,所以减少了系统的性能开销,当一个对象的产生需要比较多的资源时,如读取配置、产生其他依赖对象时,则可以通过在应用启动时直接产生一个单例对象,然后用永久驻留内存的方式来解决;
C.单例模式可以避免对资源的多重占用,例如一个写文件动作,由于只有一个实例存在内存中,避免对同一个资源文件的同时写操作。
D.单例模式可以在系统设置全局的访问点,优化和共享资源访问,例如可以设计一个单例类,负责所有数据表的映射处理。

(2)缺点
A.单例模式一般没有接口,扩展很困难,若要扩展,除了修改代码基本上没有第二种途径可以实现。

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-6 09:31

Copyright 2015-2025 djqfx

返回顶部