Singleton Pattern Example 1 – Phonebook Application

Phonebook is a listing of phone numbers along with subscriber name generally listed in alphabetical order. In this example, we want to create and maintain a phonebook with list of contacts allowing the application user to add, view and update the contact. Here, we need only one instance of phonebook which has to be accessible from everywhere. Hence, this is a perfect example for Singleton pattern.

package example.phonebook;

import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class Phonebook {

	private Map<Integer, String> contacts = 
		Collections.synchronizedMap(new TreeMap<Integer, String>());
	//static reference to itself
	private static Phonebook instance = new Phonebook();
	//private constructor
	private Phonebook() {}
	//public static method to return the reference
	public static Phonebook getInstance()
		return instance;
	public void addContact(Integer number, String name)
		contacts.put(number, name);
	public boolean editContact(Integer oldNumber, Integer newNumber, 
				String name)
			contacts.put(newNumber, name);
			return true;
		return false;
	public void viewContacts()
		Set<Map.Entry<Integer, String>> set = contacts.entrySet();
		Iterator<Map.Entry<Integer, String>> it = set.iterator();
			Map.Entry<Integer, String> entry =;
			System.out.println(entry.getKey() + ": " + 

Phonebook class maintains a static reference to an instance of itself and has a private constructor which restricts the access of constructor from outside the class. It defines a public static method getInstance() which ensures that only one instance of the class is created and returns that single instance.

Additional variable:

private Map contacts = Collections.synchronizedMap(new TreeMap());

This variable is used to store and maintain contacts.

This class defines addContact(), editContact() and viewContacts() to support adding, editing and viewing contacts from the map.

To test this Phonebook class, let’s create a PhonebookDemo class as shown below.

package example.phonebook;
public class PhonebookDemo {
	public static void main(String[] args) {
		Phonebook phBook = Phonebook.getInstance();
		phBook.addContact(1234567890, "Kumar");
		phBook.addContact(1234567000, "Peter");
		phBook.addContact(1234555890, "John");
		boolean result = 
			phBook.editContact(1234567890, 1222567890, "Kumar");
			System.out.println("Contact Edited");
			System.out.println("Contact Not Edited");

PhonebookDemo class demonstrates how to use the Phonebook class. For adding, viewing and editing the contact, we first retrieve an instance of Phonebook by calling its static getInstance() method.

1234555890: John
1234567000: Peter
1234567890: Kumar
Contact Edited

Leave a Comment