// SingletonClassDemo.java (c) Kari Laitinen // http://www.naturalprogramming.com // 2013-04-02 File created. // 2013-04-02 Latest modification. // The following class represents a counter that // could be used to count collisions in a game. // It is also an example of a so-called singleton class // of which only a single object will be created with // the get_instance() method. // By using the get_instance() method different objects // can use the same CollisionCounter object. class CollisionCounter { private int count = 0 ; private static CollisionCounter instance_of_this_class = null ; private CollisionCounter() { } public static CollisionCounter get_instance() { if ( instance_of_this_class == null ) { instance_of_this_class = new CollisionCounter() ; } return instance_of_this_class ; } public void increment() { count ++ ; } public int get_count() { return count ; } public void reset() { count = 0 ; } } class SingletonClassDemo { public static void main( String[] not_in_use ) { CollisionCounter test_counter = CollisionCounter.get_instance() ; test_counter.increment() ; CollisionCounter another_counter = CollisionCounter.get_instance() ; another_counter.increment() ; System.out.print( "\n The count is: " + test_counter.get_count() + "\n\n" ) ; } }