单例模式

2019-11-29  本文已影响0人  veneno94

饿汉模式demo:


public Simple(){

    private static Single s=new Single();     

    private Single(){}

    publicstatic Simple getSimple(){

        returns;   

    }

}

一般用于枚举法:


enum Single {

    Single;

    private Single() { }

    public void print(){

        System.out.println("hello world");

    }

}

public class SingleDemo {

    public static void main(String[] args) {

        Single a = Single.Single;

        a.print();

    }

懒汉模式 demo:


class Single1 {

    private static Single1 s = null;

    public Single1() {

    }

      //同步函数的demo

    public static synchronized Single1 getInstance() {

        if (s == null)

            s = new Single1();

        return s;

    }

    //同步代码快的demo加锁,安全高效

    public static Single1 getInStanceBlock(){

        if(s==null)

            synchronized (Single1.class) {

                if(s==null)

                    s = new Single1();

            }

            return s;

    }

}


上一篇下一篇

猜你喜欢

热点阅读