Singleton Pattern

来源:互联网 发布:zepto.js与jquery区别 编辑:程序博客网 时间:2024/04/29 03:21

Singleton Pattern:

1. Early mode

public class President{    private static President instance = new President();    private President() {}        public static President getInstance() {        return instance;    }}

2. Lazy mode:

public class President{    private static President instance;    private President() {}        public static synchronized President getInstance() {        if(instace == null){            instance = new President();        }        return instance;    }}

3. Optimize solution: (double checked locking)

public class President{    private static volatile President instance;    private President() {}        public static President getInstance() {        if(instance == null) {            synchronized(President.class){                if(instance == null){                    instance = new President();                }            }        }         return instance;    }}




0 0
原创粉丝点击