Factory Design Pattern: (Singleton Design Pattern here)
What is Factory Design Pattern?
We need to define an interface or abstract class to create an object and we allow the subclasses to decide which class to instantiate.
What is the main advantage of Factory Pattern?
The main advantage of factory pattern is Loosely-Coupling. More flexibility, We can change the implementation type without changing the dependent code.
Example,
department.java
public interface department { void Department(); }
ComputerScience.java
public class ComputerScience implements department { @Override public void Department() { System.out.println("Computer Science Department"); } }
InformationTechnology.java
public class InformationTechnology implements department { @Override public void Department() { System.out.println("Information Technology Department"); } }
FactoryPattern.java
public class FactoryPattern { public department getDepartment(String departmentChosen){ if(departmentChosen.equalsIgnoreCase("ComputerScience")){ return new ComputerScience(); } if(departmentChosen.equalsIgnoreCase("InformationTechnology")){ return new InformationTechnology(); } return null; } }
FactoryPatternExecution.java
public class FactoryPatternExecution { public static void main(String args[]){ FactoryPattern factoryPattern = new FactoryPattern(); department dept = factoryPattern.getDepartment("ComputerScience"); dept.Department(); department dept2 = factoryPattern.getDepartment("InformationTechnology"); dept2.Department(); } }
Singleton Design Pattern here
[…] Design Pattern: (Factory Design Pattern here) What is Singleton Design Pattern? Singleton Design pattern makes sure that there is only one […]