Implementing Singleton and Factory Patterns

Tutorial 2 of 5

1. Introduction

This tutorial will guide you through implementing Singleton and Factory patterns in Java. These are two of the most commonly used design patterns in software development. By the end of this tutorial, you will have a firm grasp of how these patterns work and when to use them.

What you will learn:

  • Understanding Singleton and Factory patterns.
  • Implementing Singleton and Factory patterns in Java.
  • Best practices when using these patterns.

Prerequisites:

  • Basic knowledge of Java programming and Object-Oriented Programming (OOP) concepts.

2. Step-by-Step Guide

Singleton Pattern

The Singleton pattern ensures that a class has only one instance and provides a global point of access to it.

Here's a simple Singleton implementation:

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if(instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

In the code above, we have a private constructor to prevent the creation of new instances. The getInstance() method will create a new instance only if one does not already exist.

Factory Pattern

The Factory pattern provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.

Here's a basic Factory implementation:

public interface Shape {
    void draw();
}

public class Circle implements Shape {
    public void draw() {
        System.out.println("Drawing a circle");
    }
}

public class ShapeFactory {
    public Shape getShape(String shapeType) {
        if(shapeType == null) {
            return null;
        }
        if(shapeType.equalsIgnoreCase("CIRCLE")) {
            return new Circle();
        }
        // add more shapes here...
        return null;
    }
}

In this code, ShapeFactory is a factory class that creates and returns instances of various shape classes based on provided information.

3. Code Examples

Singleton

Example of a Singleton pattern:

public class Singleton {
  private static Singleton instance;

  private Singleton() {}

  public static Singleton getInstance() {
    if (instance == null) {
      instance = new Singleton();
    }
    return instance;
  }

  public void showMessage() {
    System.out.println("Hello World!");
  }
}

public class SingletonPatternDemo {
  public static void main(String[] args) {
    Singleton singleton = Singleton.getInstance();
    singleton.showMessage(); // Output: Hello World!
  }
}

In the example above, SingletonPatternDemo uses the getInstance() method of Singleton to get an instance, and then calls showMessage() to print "Hello World!".

Factory

Example of a Factory pattern:

public interface Shape {
  void draw();
}

public class Circle implements Shape {
  public void draw() {
    System.out.println("Inside Circle::draw() method.");
  }
}

public class ShapeFactory {
  public Shape getShape(String shapeType){
    if(shapeType == null){
      return null;
    }       
    if(shapeType.equalsIgnoreCase("CIRCLE")){
      return new Circle();
    }
    return null;
  }
}

public class FactoryPatternDemo {
  public static void main(String[] args) {
    ShapeFactory shapeFactory = new ShapeFactory();

    Shape shape1 = shapeFactory.getShape("CIRCLE");
    shape1.draw(); // Output: Inside Circle::draw() method.
  }
}

In the example above, FactoryPatternDemo uses ShapeFactory to get an object of Circle and calls its draw() method.

4. Summary

We've covered the basics of implementing Singleton and Factory patterns in Java. You should now understand how these design patterns can help you control object creation and manage resources in your Java programs.

For further learning, you can explore other design patterns and understand how they can improve your code structure and efficiency.

5. Practice Exercises

  1. Exercise 1: Implement a Singleton pattern for a 'DatabaseConnection' class.

  2. Exercise 2: Create a 'CarFactory' that produces objects of different car classes (e.g., 'Sedan', 'SUV', 'Hatchback') based on provided information.

Solutions:

public class DatabaseConnection {
  private static DatabaseConnection instance;

  private DatabaseConnection() {}

  public static DatabaseConnection getInstance() {
    if (instance == null) {
      instance = new DatabaseConnection();
    }
    return instance;
  }
}
public interface Car {
  void type();
}

public class Sedan implements Car {
  public void type() {
    System.out.println("This is a Sedan");
  }
}

public class SUV implements Car {
  public void type() {
    System.out.println("This is an SUV");
  }
}

public class CarFactory {
  public Car getCar(String carType){
    if(carType == null){
      return null;
    }       
    if(carType.equalsIgnoreCase("SEDAN")){
      return new Sedan();
    } else if(carType.equalsIgnoreCase("SUV")){
      return new SUV();
    }
    return null;
  }
}

These exercises will help you gain hands-on experience with Singleton and Factory patterns. Happy coding!