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
Shape.java
public interface Shape{
      void draw();
}

Step 2: Create a concrete class using the same interface.

Rectangle.java
public class Rectangle implements shape{
    @override
    public void draw(){
   sop("rectyange");  
   }

}

Square.java
public class Square implements shape{
    @override
    public void draw(){
   sop("Square");  
   }

}

Step 3: Create a factory to generate object

ShapeFactory.java

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.

Example:

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.