Factory Method Design Pattern

1- examples that need factory design pattern ..
2- what is factory design pattern ?
3- When to use Factory design pattern ?
4- Advantage of Factory Design Pattern ?
5- How it should be implemented without Factory Design pattern ?
6- implementation with Factory method pattern ?
7- Disadvantage without using Factory Design Pattern?
8- Advantage with Factory method pattern
9- Relations with Other Patterns
10- Are Factory Design Pattern Concern with Complex object like builder?

when take about factory we will take about 3 pattern
1- static method factory (like we made in Singleton)
2- factory method (this article)
3- abstract factory method (next Article)

Example (0) Needs Factory Method Design Pattern

Guess we have 3 type of payment in your e-commerce app (Paypal+we payment + Value api)
every one of these classes has its own pay method and some of these if you use take discount

Example (1) Needs Factory Method Design Pattern

Guess we make Pokemon Go Game and we Had a lot of Pokemon that has different type(Fighting,Flying,Poison,Ground,Rock,…),Strong Against,Weak Against,Resistant To and Vulnerable To beside action when attack or defense so Pokemon are classified into groups

  • we can’t make big general class contain a lot of switch or if-else condition for all item and if we do it will make testing and maintainability will be hard
  • make class for each one and use them directly (will take about disadvantage)

Example (2) Needs Method Factory Design Pattern

Guess we make e-commerce app that has more that user
1- client make shopping
2- distinguished Client make shopping.(with EXTRA discount)
3- owner that can post his own product can make shopping (product similler to his offer)

they all some common property and function but other has another implementation for function and other has extra function

  • we can’t encapsulate them in one class this against SOLD Principle may i can another article for it
  • if another type added to db we will go inside that class and edit in it also against SOLD Principal

Examples (3) Needs Method Factory Design Pattern

if we want to handle currency in e-commerce app
every currency has country + symbol like $ +name like EURO

many choice

Factory Method Pattern says that just define an interface or abstract class for creating an object but let the subclasses decide which class to instantiate.

Example in Dagger

  • Dagger allows you to inject the Provider of any type available on the dependency graph and this provider can be easily mapped to ViewModelProvider.Factory.

When to use Factory design pattern :

  1. Factory method is used when Classes don’t need to know how they are created.
  2. We can use factory pattern where we have to create an object of any one of sub-classes depending on the data provided
  3. Use the Factory Method when you want to provide users of your library or framework with a way to extend its internal components.
  4. Some or all concrete classes can be created in multiple ways, or we want to leave open the option that in the future there may be new ways to create the concrete product.
  5. Use the Factory Method when you want to save system resources by reusing existing objects instead of rebuilding them each time.
  6. Use the Factory Method when you don’t know beforehand the exact types and dependencies of the objects your code should work with.
  7. This is helpful when an object needs to be created from a family of classes.

how it should be implemented abstraction ?

  1. All the subclasses should implement the interface so that every class will have the same methods.
  2. All the objects should be created in a subclasses and they all implement a specific function that we define in an Interface.

Implementation Without Factory Design pattern

here client code will use that view inside setContentView()

Disadvantages Without using Factory Pattern

  • all our classes are exposed to clients. It means, there is a tight coupling between consumer(use classes) and the classes . Due to this tight coupling classes cannot be changed in future without breaking clients’ code. mean if you change Triangle class you will need go to client class to update your change so The classes modification are hard due to tight coupling
  • if we remove square as it it special triangle as width = height , then the Clients using Square class cannot be compiled anymore, because those Clients are tightly coupled with the Square class.
  • The classes cannot be modified due to tight coupling

Implementation with Factory Design Pattern

Steps

1- Create a public interface for all your similar classes as the template.

2- Try to keep all the subclasses in the default access level(assume we will make Graphic Library 😅😅). or make private to make consumer who can’t use these subclass

3- Create a factory class with one or more than one methods to produce the objects with a return type of super interface.

will handle these classes”.It will return the best object based on the input
  • Clients cannot access any of the sub-classes of Shape interface, due to their default (package private) access level (Only accessible within the package). The only way to create a Shape object is using the ShapeFactory by providing the required Shape type. According to this design, a client does not need to know the sub-classes. Even they do not need to worry about the logic behind object creation (They are not required to be an expert in geometry).
  • Additionally, if you want to remove the Square class as mentioned earlier, it can be done easily without breaking the client just edit in ShapeFactory .
when (type) { 
Type.CIRCLE -> shape = Circle(paint, canvas, radius)
Type.SQUARE -> shape = Rectangle(paint, canvas, width, width)
Type.RECTANGLE -> shape = Rectangle(paint, canvas, width, height) }
Client Code to use Class

Advantage of Factory Design Pattern :

1- clients have access to Shape interface and ShapeFactory class only.
2- Remove the code duplication using the factory class and method.
3- Subclass implementations are independent of application clients, hence enforce flexibility, maintainability, and testability (imagine how we will test class that contain all type and use if-else to choose function)
4- Eliminate many run-time errors due to service delegation to the factory
class
5- Maintain the code consistency through consolidating object creation mechanism within the factory class.
6- Encourage the programming to interface principle ensuring the code quality of the system
7- to add a new shape type to the app, you’ll only need to create a new creator subclass and override the factory method in it.
8- reduce the code that constructs components into a single factory method and let anyone override this method in addition to extending the component itself.

Disadvantage of Factory Design pattern

  • The code may become more complicated since you need to introduce a lot of new subclasses to implement the pattern.

Factory Method Pattern and Solid Principal?

  • Single Responsibility Principle. You can move the product creation code into one place in the program, making the code easier to support.
  • Open/Closed Principle. You can introduce new types of products into the program without breaking existing client code.

Relations with Other Patterns

  • Sometimes creational patterns are complementary: Builder can use one of the other patterns to implement which components get built. Abstract Factory, Builder,and Prototype can use Singleton in their implementations.

here we make FactoryShap as Singleton design pattern u can make it as i told in Singleton design Pattern

  • Many designs start by using Factory Method (less complicated and more customizable via subclasses) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, but more complicated).
  1. Abstract Factory classes are often based on a set of Factory Methods, but you can also use Prototype to compose the methods on these classes.
  2. You can use Factory Method along with Iterator to let collection subclasses return different types of iterators that are compatible with the collections.
  3. Prototype isn’t based on inheritance, so it doesn’t have its drawbacks. On the other hand, Prototype requires a complicated initialization of the cloned object. Factory Method is based on inheritance but doesn’t require an initialization step.
  4. Factory Method is a specialization of Template Method. At the same time, a Factory Method may serve as a step in a large Template Method.

Are Factory Design Pattern Concern with Complex object like builder?

  • Builder focuses on constructing a complex object step by step.
    Abstract Factory emphasizes a family of product objects (either simple or complex).
  • Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.

So they are pattern came to solve problem if problem not exit please don’t do it

- we can create objects by calling a factory method rather by calling a constructor

- subclasses are responsible to create the instance of the class.

- The Factory Method Pattern is also known as Virtual Constructor.

- Factory pattern provides approach to code for interface rather than
implementation

- Factory pattern removes the instantiation of actual implementation classes from client code, making it more robust, less coupled and easy to extend.

- Factory pattern provides abstraction between implementation and client classes through inheritance.

Conclusion

The Factory Pattern is an OOP design pattern where a client requests one object to create an instance of another object for it. The actual object is normally hidden behind an interface to allow for loose coupling, but the factory knows how to produce the correct object. Let’s consider for example a client that needs a product.

Mobile Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store