Common design patterns Ask in Software Engineer interview

 Common design patterns Ask in Software Engineer interview

Common design patterns Ask in Software Engineer interview

The two most commonly asked design patterns in Software Engineering interviews are.

πŸ‘‰01. Singleton Design Pattern
πŸ‘‰02. Factory Design pattern 

Both the design pattern are creational design patterns it means It gives the way to create objects while hiding creation logic.

πŸ‘‰01. Factory Design Pattern
In the Factory design pattern, we create objects without exposing the creation logic to the client and refer to newly created objects using a common interface.

Steps in creating Factory design Pattern

Step 1: Create an interface
public interface Shape{
      void draw();

Step 2: Create a concrete class using the same interface.
public class Rectangle implements shape{
    public void draw(){

public class Square implements shape{
    public void draw(){


Step 3: Create a factory to generate object

public class ShapeFactory{

public shape getShape(String shape){

       if(shape == null) return null;
       if(shape.equals("Square") ) return new Square();
       if(shape.equals("Rectangle")) return new Rectangle();

return null;

πŸ‘‰02. Singleton Design Pattern
Used to create singleton class and singleton class is a class that can have only one object at a time.

Steps to create Singleton design pattern

πŸ‘‰01. Mark the constructor private.
πŸ‘‰02. Create a private static class variable.
πŸ‘‰03. Create a public method to create an object after checking if the object is not already created.


class Singleton{

private static Singleton obj = null;

private Singleton(){}

public static singleton getInstance(){

     if(obj == null) obj = new Singleton();
return obj;



πŸ““ We can make Singleton class thread-safe in the following ways:
πŸ‘‰ mark the method to get instance synchronized (WORST)
πŸ‘‰ mark the code block of creating an object as synchronized (BETTER)
πŸ‘‰ Create an instance using enum INSTANCE; (BEST)

No comments:

For Query and doubts!

Powered by Blogger.