SINGLETON AND FACTORY PATTERN

patterns often defined as many ways of providing communication between different entities in an object-oriented manner, here I have given example of two basic patterns.

  1. Singleton pattern.
    This pattern is the simplest of all the patterns out there. the main aim is to make sure that we create no more than one instance of our class we do this by making our constructor as private. The below code gives the lazy initialization method.
public class SingletonClass {
private static SingletonClass SINGLE_INSTANCE = null;
private SingletonClass() {}
public static SingletonClass getInstance() {
if (SINGLE_INSTANCE == null) {
synchronized(SingletonClass.class) {
SINGLE_INSTANCE = new SingletonClass();
}
}
return SINGLE_INSTANCE;
}
}

2. Factory Pattern
The factory pattern is one of the most used design patterns in Java. This type of design pattern comes under a creational pattern as this pattern provides one of the best ways to create an object.

In the Factory pattern, we create an object without exposing the creation logic to the client and refer to the newly created objects using a common interface.

FACTORY PATTERN USING INTERFACE

//INTERFACE
public interface Shape {
void draw();
}

FACTORY PATTERN USING ABSTRACT CLASS

import java.io.*;      
abstract class Plan{
protected double rate;
abstract void getRate();

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store