Singleton Pattern Example in Java

This is the simple but important java exercise about Singleton Pattern. The purpose of this code is to understand the Singleton Pattern. After doing this java exercise you will be able to understand what is Singleton Pattern? How Singleton Pattern work and why we need Singleton Pattern?


Source Code 



import java.util.*;

public class SingletonTask{
 public static void main(String [] args)
 {
  Whiteboard wb = Whiteboard.getInstance();
  Reader r1 = new Reader();
  Reader r2 = new Reader();
  Reader r3 = new Reader();
  
  Sender s1 = new Sender();
  Sender s2 = new Sender();
  Sender s3 = new Sender();
  Sender s4 = new Sender();
  Sender s5 = new Sender();
  
  s1.post("message from Sender 1");
  s2.post("message from Sender 2");
  s3.post("message from Sender 3");
  
  System.out.println(r1.read(3));
  
  s4.post("message from Sender 4");
  s5.post("message from Sender 5");
  s2.post("message from Sender 2");
  
  System.out.println(r2.read(5));
  
  s1.post("message from Sender 1");
  
  System.out.println(r3.read(7));
  System.out.println(r2.read(1));
 }
 
 
};

class Whiteboard{
 private static Whiteboard instance;
 private ArrayList<String> messages;
 
 private Whiteboard() {
  messages = new ArrayList<String>();
 }
 
 public void addMessage(String msg)
 {
  messages.add(msg);
 }
 
 public String readMessage(int i)
 {
  if(i <= messages.size())
  {
   String msg = messages.get(i-1);
   messages.remove(i-1);
   return msg;
  }
  return "Error: Out of range!";
 }
 
 public static Whiteboard getInstance(){
  if(instance == null)
   instance = new Whiteboard();
  
  return instance;
 }
}

class Reader{
 private Whiteboard whiteboard;
 
 public Reader()
 {
  whiteboard = Whiteboard.getInstance();
 }
 
 public String read(int i)
 {
  return whiteboard.readMessage(i);
 }
}

class Sender{
 private Whiteboard whiteboard;
 
 public Sender()
 {
  whiteboard = Whiteboard.getInstance();
 }
 
 public void post(String msg)
 {
  whiteboard.addMessage(msg);
 }
}

Output of the Program 

Singleton Design Pattern in Java

Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.

1 comments:

  1. When i run this Program then there is one output in which a message display " Error Out of range ! " What is mean by this one ??

    ReplyDelete