/*
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("单例");
}
}