单例设计模式

单例模式即只有一个对象

//饿汉式

bank bank1 = bank.getInstance ( ) ;

class bank{

1.私有化构造器

private bank ( ) {

}

2.内部创建类的对象

4.要求此对象也必须声明为静态的

private bank instance = new bank( ) ;

3.提供公共的静态方法,返回类的对象

public static bank getInstance( ) {

  return instance ; 

}

}

此时无论创建多少对象都指向同一个地址值

//懒汉式

class order{

1.私有化构造器

private order( ) {

}

2.在内部创建对象,但没有初始化

4.此对象也必须为静态的

private static order init = null ;

3.声明公共的静态的返回对象的方法

public static order getInstance{

     if( init == null )

  init = new order( ) ;

return init ;

}

posted @ 2022-10-21 18:59  平凡的柳先生  阅读(22)  评论(0)    收藏  举报