设计模式-单例模式

什么是单例模式?

一个类在一个系统中只有一个实例,在类中自行实例化并且提供给系统统一的访问接口。

单例模式的应用场景

1.日志系统:在应用程序中,通常只需要一个日志系统,所以只创建一个实例以降低资源损耗。
2.数据库连接池:同样,应用程序一般只允许存在一个数据库连接池,避免资源浪费。
3.文件管理器:在应用程序中,通常只需要一个配置文件管理器来管理应用程序的配置文件,单例模式可以确保在整个应用程序中只有一个配置文件管理器实例。
4.缓存系统:在应用程序中,缓存系统是一个重要的组件,单例模式可以确保在整个应用程序中只有一个缓存实例,以提高应用程序的性能。
5.GUI组件:在图形用户界面(GUI)开发中,单例模式可以确保在整个应用程序中只有一个GUI组件实例,以确保用户界面的一致性和稳定性。(讲真,这块没了解过)
总结:单例模式适用于只需要一个实例的场景,以满足实例的高效利用。

单例模式的表现形式

饿汉式:类加载时,就进行实例化
请忽略英文注释,作者没事写着玩的

public class SingletonPattern {
    /**
     * brief introduction:
     * A class in a system has only one instance,
     * which is self instantiated within the class and provides a unified access interface to the system;
     * this pattern have two types:
     * Hungry man type:when a class loading,instantiate it
     * sluggard type:when a class is first interfaced,instantiate it
     */
    private volatile static  SingletonPattern singletonPattern;
    private SingletonPattern(){}

    /**
     * Hungry man type
     */
    public static SingletonPattern getHungryInstance(){
        return singletonPattern;
    }

懒汉式:类加载时不会进行实例化,只有当类被引用时,才进行实例化;当然,这样会存在一种问题,多线程访问时会存在创建多个实例的问题

   /**
     * sluggard type
     * problem:
     * if multiple threads access this class,
     * this class maybe multiple instances created,
     * because getSluggardInstance() can not ensure synchronization.
     * @return
     */
    public static  SingletonPattern getSluggardInstance(){
        if(singletonPattern==null){
            singletonPattern=new SingletonPattern();
        }
        return singletonPattern;
    }

可以用synchronized关键字简单处理下,

 /**
     * so,we can using "synchronized" keywords process code blocks,
     * and using "volatile" keywords process variable.
     */
    public static SingletonPattern getSyncSingletonPattern(){
        if(singletonPattern==null){
            synchronized(SingletonPattern.class){
                singletonPattern=new SingletonPattern();
            }
        }
        return singletonPattern;
    }

单例模式的优缺点

优点
提供对唯一实例的受控访问;
相较于频繁创建和销毁的对象,单例模式在系统资源开销上更具优势;
单例模式可以允许可变的数目的实例,使用单例模式进行扩展,使用控制单利对象相似的方法获取指定个数的实例,及解决了单利对象,共享过多,而有损性能的问题;
缺点
单例模式不是抽象的,所以扩展性很差;
单例模式意味着职责过重,这违背了单一职责;
单例模式的不规范使用可能导致负面影响,如java的垃圾回收机制在实例化对象长时间未被使用的情况下销毁回收实例化对象,导致单例对象状态的丢失。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值