Studyon Minte9.com
Head First (Patterns)




Singleton Pattern



	%java
		package testexample;

		public class Testexample {

		    public static void main(String[] args) {
			
			Testexample t = new Testexample();
		    }
		    
		    public Testexample() {

			System.out.println(new Client().property++); // output 0
			System.out.println(new Client().property++); // output 0
			    // Incorect
			    // We want property to keep it's state
			
			//System.out.println(new Client2().property++);
			    // Error: Client2() has private access
			
			System.out.println(ClientS.getInstance().property++); // output 0
			System.out.println(ClientS.getInstance().property++); // output 1
			    // Corect
		    }
		}

		class Client {

		    public Client() {}
		    public int property = 0;
		}


		class ClientS { // Singleton

		    private ClientS() {}
		    public int property = 0;
		    
		    private static ClientS c = new ClientS();
		    
		    public static ClientS getInstance() {
			return c;
		    }
		}