饿汉式步骤:
class Bank{
//1.私有化构造器
private Bank(){
}
//2.内部创建类的对象
//4.要求此对象也必须声明为静态
private static Bank instance=new Bank();
//3.提供公共的静态的方法,返回类的对象
public static Bank getInstance(){
return instance;
}
}
public class SingletonTest {
public static void main(String[] args) {
Bank bank1=Bank.getInstance();
Bank bank2=Bank.getInstance();
System.out.println(bank1==bank2);
}
}
懒汉式步骤:
public class SingletonTest2 {
public static void main(String[] args) {
Order order=Order.getInstance();
Order order1=Order.getInstance();
System.out.println(order==order1);
}
}
class Order{
//1.私有化构造器
private Order(){
}
//2.内部创建类的对象
//4.要求此对象也必须声明为静态
private static Order instance=null;
//3.提供公共的静态的方法,返回类的对象
public static Order getInstance(){
if (instance==null){
instance=new Order();
}
return instance;
}
}
|