## Simple Factory Programming Idiom ![[Screenshot 2023-09-03 at 10.01.52 PM.png]] ![[Screenshot 2023-09-03 at 4.15.41 PM.png]] This is not a full fledged design pattern because the factory class is still open for modification. When new pizzas are added to the menu, new if statements will need to be added to the class to accommodate for the new concrete products. ## Factory Method Pattern The Factory Method Pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses. * A factory method handles object creation and encapsulates it in a subclass. This decouples the client code in the superclass from the object creation code in the subclass. ![[Screenshot 2023-09-03 at 10.28.38 PM.png]] ### Q: When should the Factory Method Pattern be used ? Use the pattern if you have no idea of the exact types of the objects your code will work with. This is because it makes it easy to extend the product construction scope independently from the rest of the application. Allowing the introduction of new products without breaking existing code. ### Q: What is the difference between the Simple Factory and Factory Method ? Compared with Simple Factory, which give us a way to encapsulate object creation, but does not give us the flexibility of the Factory Method because there is no way to vary the products we are creating. In the factory method, by subclassing the abstract creator class, the concrete creators decide what products are made and returned. ## Abstract Factory Pattern The Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes. ![[Screenshot 2023-09-03 at 11.25.38 PM.png]] * The abstract factory pattern suggest to declare interfaces for each distinct product we have and then make all variants of our products follow those interfaces. ### Q: When should I Use the Abstract Factory Pattern ? * Use it when your code needs to work with various families of related products, but you don't want it to depend on the concrete classes of those products. * Many designs start by using the Factory Method Pattern and later evolve toward an Abstract Factory Design. ### QA: * The intent of **Factory Method** is to allow a class to defer instantiation to its subclasses. * The intent of **Abstract Factory** is to create families of related objects without having to depend on their concrete classes. ### Q: What are the benefits of factories ? By placing all creation code in one object or method, code duplication is avoided and provide one place to perform maintenance. That also means clients depend only upon interfaces rather than the concrete classes required to instantiate objects. This allows for programming to interfaces, not implementations, making the code more flexible and extensible in the future.