publicclassSingletonTest1{ publicstaticvoidmain(String[] args){ // Bank bank1 = new Bank(); // Bank bank2 = new Bank(); Bank bank1 = Bank.getInstance(); Bank bank2 = Bank.getInstance(); System.out.println(bank1 == bank2); } }
//饿汉式 classBank{ //1.私有化类的构造器 privateBank(){ } //2.内部创建类的对象 //4.要求此对象也必须声明为静态的 privatestatic Bank instance = new Bank(); //3.提供公共的静态的方法,返回类的对象 publicstatic Bank getInstance(){ return instance; } }