设计模式---单例模式

打印 上一主题 下一主题

主题 897|帖子 897|积分 2691

简述


  • 类型:创建型。
  • 目的:杜绝相同对象的反复创建,提升系统性能。
话不多说,直接看实现方案例。
实现案例

饿汉式

项目启动时加载
  1. public class Test {
  2.     private static Test ins = new Test();
  3.     public static Test instance() {
  4.         return ins;
  5.     }
  6. }
复制代码
在项目启动时就被加载 → 项目启动变慢
如果对象不经常使用的话还存在浪费资源的问题。
懒汉式

懒加载,在使用时才被加载
  1. public class Test {
  2.     private static Test ins;
  3.     public static synchronized Test instance() {
  4.         if (ins == null) ins = new Test();
  5.         return ins;
  6.     }
  7. }
复制代码
在项目启动时并不加载 → 项目加载变快
第一次使用时加载 → 存在第一次使用时等待过长的问题
使用synchronized方法 → 性能下降
懒汉式(优化版)

懒加载,在使用时才被加载(解决并发的性能问题)
  1. public class Test {
  2.     private static Test ins;
  3.     public static Test instance() {
  4.         if (ins == null) {
  5.             synchronized (Test.class) {
  6.                 if (ins == null) ins = new Test();
  7.             }
  8.         }
  9.         return ins;
  10.     }
  11. }
复制代码
在项目启动时并不加载 → 项目加载变快
第一次使用时加载 → 存在第一次使用时等待过长的问题
使用双重判断方法 → 相对优化前性能提升
不推荐使用
静态内部类(懒汉式)

懒加载,在使用时才会被加载(无并发性能问题)
  1. public class Test {
  2.     private static Singleton {
  3.         private static final Test ins = new Test();
  4.     }
  5.     public static Test instance() {
  6.         return Singleton.ins;
  7.     }
  8. }
复制代码
在项目启动时并不加载 → 项目加载变快
第一次使用时加载 → 存在第一次使用时等待过长的问题
推荐使用
枚举(饿汉式)
  1. public enum Test {
  2.     INSTANCE;
  3.     public static Test instance() {
  4.         return INSTANCE;
  5.     }
  6. }
复制代码
在项目启动时就被加载 → 项目启动变慢
如果对象不经常使用的话还存在浪费资源的问题。
推荐使用
总结

优点


  • 减少对象的创建次数,提高系统性能。
缺点


  • 由于是静态资源,所以增加了内存上的负担。
适用场景


  • 避免资源的互斥(见样例)
    1. public class Test {
    2.     private FileWriter fw;
    3.     public void write(String fileName, String data) throws IOException {
    4.         fw = new FileWriter(fileName);
    5.         fw.write(data);
    6.     }
    7. }
    复制代码
    这段代码可能会有问题:当多个Test对象对同一个fileName写入时,由于FileWriter的父类Writer中定义的write有一把对象锁,多个FileWriter就导致有多把锁,无法做到互斥,就会出现错误。
  • 全局唯一类(工具类等)

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

盛世宏图

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表