Assume we have a system that can manage online users.In there, system is counting user login events and user logout events.This is like a log file.The whole system needs only one log file and it is maintaining accurate user count.
Here a sample class file created for above scenario.Refer this code and try to understand the behavior of singleton pattern.
--source code can be not loaded because of network issues--
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Singleton { | |
private static Singleton instance=null; | |
int online_usercount; | |
private Singleton(){ | |
online_usercount=0; | |
/*As this constructor private Singleton do not support inheritance.*/ | |
} | |
public static Singleton getInstance(){ | |
if(instance==null){ | |
instance=new Singleton(); | |
} | |
return instance; | |
} | |
public void userLogin(){ | |
online_usercount++; | |
} | |
public void userLogout(){ | |
online_usercount--; | |
} | |
public int getOnlineUserCount(){ | |
return online_usercount; | |
} | |
} | |
public class Onlineuser { | |
public static void main(String args[]){ | |
Singleton s1=Singleton.getInstance(); | |
//Initializing s1 objects || We can directly call 'getInstance()' because it is static method. || Now online_usercount=0 | |
Singleton s2=Singleton.getInstance(); | |
s1.userLogin(); //online_usercount=1 | |
s1.userLogin(); //online_usercount=2 | |
s1.userLogout(); //online_usercount=1 | |
s1.userLogin(); //online_usercount=2 | |
s2.userLogin(); | |
System.out.println("s1 online user count :"+s1.getOnlineUserCount()); | |
System.out.println("s2 online user count :"+s2.getOnlineUserCount()); | |
if(s1.equals(s2)){ | |
System.out.println("****Singleton Design Pattern Is Working****"); | |
} | |
} | |
} |
0 comments:
Post a Comment
Leave your comment and feedback here for me