java - Creating only 1 instance or a Singleton -


i used class called 'city' & there 1 city in entire game; beneficial create instance, if 1 or singleton.

the class contain methods won't static, & i've read singletons consist of static attributes , methods & can bad practice or mistaken?

singleton common pattern , can deal 1 instance of object inside entire runtime environment. don't warry distinguish static , non-static methods... make of them non-static, because if invoke them city.getinstance().method() , sure method() (and other method) invoked on same instance.

previous answer correct, have implement singleton in different way if in multi-thread environment (as web application) , need sure 1 instance created.

infact, in prevoius code possible several concurrent threads create new city instance... threads created later use last instance (because overrides first 1 in static field).

there several options overpass problem... common make synchronized getinstance() method:

public static synchronized city getinstance() { 

a efficient (in high-concurrent environment) use lazy initialization:

public class city {      private static volatile city instance;      public static city getinstance() {         if( instance == null ) {             synchronized (city.class) {                 if( instance == null ) {                     instance = new city();                 }             }         }         return instance;     }      private city() {       ... construct city here ....     }      // city instance methods here (non-static)     ....  } 

somewhere see implementation based on initialization on class "on demand"...


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -