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…
Section overview
5 resourcesCovers 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
-
Exercise 1: Implement a Singleton pattern for a 'DatabaseConnection' class.
-
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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article