Factory Design Pattern in java

When to use Factory Design Pattern :

The Factory Method pattern is generally used in the following situations:

  • A class cannot anticipate the type of objects it needs to create beforehand.
  • A class requires its subclasses to specify the objects it creates.
  • You want to localize the logic to instantiate a complex object.

Points on Factory Design Patterns

  • Belongs to creational design patterns
  • Low coupling and more cohesion
public interface OS {
	void printOsName();
}

public class Linux implements OS{
	@Override
	public void printOsName() {
		System.out.println("This is linux operating system");
	}
}

public class IOS implements OS{
	@Override
	public void printOsName() {
		System.out.println("This is IOS operating system");
	}
}

public class Windows implements OS{
	@Override
	public void printOsName() {
		System.out.println("This is windows operating system");
	}
}

public class OSFactory {
	public OS getOsInstance(String input) {
		if(input.equalsIgnoreCase("Secure")) {
			return new IOS();
		}else if(input.equalsIgnoreCase("MostUsed")) {
			return new Windows();
		}else {
			return new Linux();
		}
	}
}

public class FactorDesignPatternDemo {
	public static void main(String[] args) {
		OS obj;
		obj = new OSFactory().getOsInstance("MostUsed");
		obj.printOsName();
		obj = new OSFactory().getOsInstance("Secure");
		obj.printOsName();
		obj = new OSFactory().getOsInstance("Others");
		obj.printOsName();
	}
}

Read Me : (Reference)

Leave a Comment