编程语言
首页 > 编程语言> > 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,getInstance,Mgr01,private,INSTANCE,static,单例,设计模式,public
来源: https://www.cnblogs.com/huaweidog/p/16349041.html