Sunday, September 12, 2021

Factory Method - Real Time Use

 Making it simple silly...

Ques: When to use factory pattern?

Answer: -


By Name: - When we want to create a factory, which will produce different objects based on some parameters.


By Use : - When specific object is required to be instantiated after certain conditions/algorithm/logic we put that object creation logic in a method (called factory method) to reuse it from multiple places. Object instantiation requires certain parameters to process those conditions/algorithm/logic and return the desired object.


By Example :-


interface IMobile { void CreateMobile(); } public class Samsung : IMobile { public void CreateMobile() { Console.WriteLine("Samsung Mobile Created"); } } public class OnePlus : IMobile { public void CreateMobile() { Console.WriteLine("OnePlus Mobile Created"); } } // 1. This MobileFactory can be reusable. // 2. There is actally a processsing logic only after which it creates a required mobile object. // 3. The intention is to hide the complexity of this processing logic from calling classes. internal class MobileFactory { internal IMobile CreateMobile(String objectKey) { switch (objectKey) { case "samsung": //Some processing logic return new Samsung(); case "onePlus": //Some processing logic return new OnePlus(); default: throw new KeyNotFoundException(); } } } class Program { static void Main(string[] args) { MobileFactory myFact = new MobileFactory(); OnePlus onePlus = myFact.CreateMobile("onePlus") as OnePlus; onePlus.CreateMobile(); Console.ReadKey(); } }