package com.anby.Singleton;
//为了创建全局唯一的对象,则使用单利模式 public class SingletonDemo { /** * @param args */ public static void main(String[] args) { SingleA singleA=SingleA.getInstance(); SingleB singleB=SingleB.getInstance(); } } // 懒汉式 class SingleA { private static SingleA uniqueSingleA; private SingleA() { } public synchronized static SingleA getInstance() { if (uniqueSingleA == null) { uniqueSingleA=new SingleA(); } return uniqueSingleA; } } //饿汉式 class SingleB { private static SingleB uniqueSingleB=new SingleB(); private SingleB() { } public synchronized static SingleB getInstance() { return uniqueSingleB; } }