Java / Java Design Patterns

Implementing Singleton and Factory Patterns

This tutorial focuses on the implementation of Singleton and Factory Patterns in Java. It will provide a deep understanding of how these patterns can be used to control object cre…

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Covers design patterns to solve common software development problems.

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!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

HTML Minifier & Formatter

Minify or beautify HTML code.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help