java单例模式

来源:互联网 发布:linux 添加用户组 编辑:程序博客网 时间:2024/05/16 05:39
/*ios中没有类成员变量,即类中的静态成员变量,只有类方法(+开头的方法);利用静态全局或静态局部变量作为单例。dispatch_once提供了线程安全,且执行一次,省去了if(xx==nil)的判断。*/public class AppEnter{public static void main(String[] args) {Singleton instance = Singleton.sharedInstance();instance.show();Singleton instance1 = Singleton.sharedInstance();System.out.println(instance == instance1);}}class Singleton{//第一步:类对象private static Singleton instance /*= new Singleton()饥饿式*/;//第二步:私有的构造函数private Singleton(){}//第三步:对外公共获取方法public static Singleton sharedInstance(){if (instance == null) {//懒汉式instance = new Singleton();}return instance;}public void show(){System.out.println("单例");}}

0 0
原创粉丝点击