Java教程

java 设计模式-单例模式

本文主要是介绍java 设计模式-单例模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一·单例模式

保证内存中只有一个实例

方法1:用private修饰构造方法

package singleton;

public class Mgr01 {
    private static final Mgr01 INSTANCE = new Mgr01();

    private Mgr01(){};

    public static Mgr01 getInstance(){return INSTANCE;};

    public void m(){
        System.out.println("m");
    }

    public static void main(String[] args) {
        Mgr01 m1 = Mgr01.getInstance();
        Mgr01 m2 = Mgr01.getInstance();
        System.out.println(m1 == m2);

    }
}

方法2:定义静态语句块

package singleton;

public class Mgr01 {
    private static final Mgr01 INSTANCE;

    static {
        INSTANCE = new Mgr01();
    }

    private Mgr01(){};

    public static Mgr01 getInstance(){return INSTANCE;};

    public void m(){
        System.out.println("m");
    }

    public static void main(String[] args) {
        Mgr01 m1 = Mgr01.getInstance();
        Mgr01 m2 = Mgr01.getInstance();
        System.out.println(m1 == m2);

    }
}

 方法3:懒汉式,线程不安全,使用时需要加锁,会降低效率

package singleton;

public class Mgr01 {
    private static Mgr01 INSTANCE;

    private Mgr01(){};

    public static Mgr01 getInstance(){
        if(INSTANCE == null){
            INSTANCE = new Mgr01();
        }
        return INSTANCE;
    };

    public void m(){
        System.out.println("m");
    }

    public static void main(String[] args) {
        Mgr01 m1 = Mgr01.getInstance();
        Mgr01 m2 = Mgr01.getInstance();
        System.out.println(m1 == m2);

    }
}

 

 

 方法4: 从静态内部类获取实例,相比方法1,只有在调用getInstance的时候才会加载静态内部类,即实现了懒加载,又保证线程安全

package singleton;

public class Mgr01 {

    private Mgr01(){};

    private static class Mgr01Holder{
        private static final Mgr01 INSTANCE = new Mgr01();
    }

    public static synchronized Mgr01 getInstance(){
        return Mgr01Holder.INSTANCE;
    };

    public void m(){
        System.out.println("m");
    }

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> System.out.println(Mgr01.getInstance().hashCode())).start();
        }

    }
}

方法5:枚举单例

package singleton;

public enum Mgr08 {
    INSTANCE;

    public void m(){}

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> System.out.println(Mgr08.INSTANCE.hashCode())).start();
        }
    }
}

 

这篇关于java 设计模式-单例模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!