设计模式之单例模式

一、概论

1.所谓单例就是只有一个实例(对象),

2实现的思路是将构造方法私有化,对外提供一个获取该实例的静态方法,(有则返回,无则创建再返回)

3.其他类就可以根据这个对象调用这个类中的方法。

二、为什么要学习单例模式

1.解决资源共享和资源控制相关问题,如:网站计数器,windows的任务管理器、垃圾回收站,日志等

2.全局使用的类的实例频繁的创建和销毁,耗用大量不必要的系统资源

三、几种实现方式的实例代码

1.懒汉式(非线程安全)

   特点:属于懒加载(具体需要时才实例化),非线程安全,

  实例代码:

/**
 * 懒汉式,线程不安全,不支持多线程,没有加synchronized
 */
public class Singleton1 {
    private static Singleton1 singleton1;
    private Singleton1(){}//构造方法私有,其他类无法实例化
    //对外提供一个获取该实例对象的方法
    public static Singleton1 getInstance(){
        if (singleton1 == null){
            singleton1 = new Singleton1();
        }
        return singleton1;
    }
    //以下定义多个共享的方法
    public void display(){}
}

2.懒汉式(线程安全)

   特点:懒加载,线程安全

   实例代码:

public class Singleton2 {
    
    private static Singleton2 singleton2;
    
    private Singleton2(){}
    
    public static synchronized Singleton2 getInstance2(){
        if (singleton2 == null){
            singleton2 = new Singleton2();
        }
        return singleton2;
    }
    //其他共享方法
    public void otherMethod(){}
}

3.饿汉式

   特点:非懒加载,线程安全

  实例代码:

public class Singleton3 {
    private static Singleton3 singleton3 = new Singleton3();
    private Singleton3 (){}
    public static Singleton3 getInstance3(){
        return singleton3;
    }
}

4.双重检验锁方式

   特点:懒加载,线程安全

  实例代码:

/**
 * 双重检验锁,多线程下高性能
 */
public class Singleton4 {
    private volatile static Singleton4 singleton4;
    private Singleton4(){}
    public static Singleton4 getInstance4(){
        if (singleton4 == null){
            synchronized (Singleton4.class){
                if (singleton4 ==null){
                    singleton4 = new Singleton4();
                }
            }
        }
        return singleton4;
    }
}

5.内部类方式

  特点:懒加载,线程安全

  实例代码:

/**
 * 静态内部类方式
 */
public class Singleton5 {
    //内部类
    private static class Singleton{
        private static final Singleton5 singleton = new Singleton5();
    }
    private Singleton5(){}
    public static final Singleton5 getInstance5(){
        return Singleton.singleton;
    }
}

//以上内容来源于网络,纯属个人学习做记录,欢迎大家批准、指正、提议!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章