Agenda

In this article we will understand:

Previous Articles

  1. Design Patterns: Introduction
  2. Learn Design Pattern - Singleton Pattern

Definition

The Factory Method Pattern is the most commonly used design pattern in modern programming and it falls under the Creation Pattern; in other words it is related to object creation.

According to the Gang of Four: the "Factory Method Pattern defines an interface for creating an object, but let the subclasses decide which class to instantiate".
(We will explain this definition as we move further.)

When to use

Consider a situation

where a person that wants something first creates it and then uses it.

Example: if he wants to eat a "Good day biscuit" then he first creates it and then eats it, and when he wants "Parle G" he changes his creation method to create it and then eat it.

It's very difficult for him to survive if he keeps on constructing everything by himself. He wants someone (some kind of factory) to do this construction work for him so that he can concentrate on more important aspects of life.

Sorry if it's not a good example, I am not a creative guy, but I hope you understood what I was trying to explain.

Practical Example

Our Company ABC Corporation currently has 3 levels of customers Grade1, Grade2 and Grade 3.
Grade1 - > A Tax of 12% will be applied to the total amount
Grade2 - > A Tax of 30% will be applied to the total amount
Grade3 - > A Tax of 40% will be applied to the total amount

Our task is to create an option which will ask for Customer Name, Grade and Amount as input and display Final Amount.

Output

output-design-pattern.jpg

Coding

1. Create the Entities required like:

  1. public class Grade1Customer
  2. {
  3. public string CustomerName { get; set; }
  4. public int Amount { get; set; }
  5. public int GetTotalAmount()
  6. {
  7. return (int)(Amount + (Amount * 0.12));
  8. }
  9. }
  10. public class Grade2Customer
  11. {
  12. public string CustomerName { get; set; }
  13. public int Amount { get; set; }
  14. public int GetTotalAmount()
  15. {
  16. return (int)(Amount + (Amount * 0.30));
  17. }
  18. }
2. Create the ASPX page and the following code behind:
  1. switch(DdlGrade.SelectedValue)
  2. {
  3. case "1":
  4. {
  5. Grade1Customer obj = new Grade1Customer()
  6. {
  7. CustomerName = TxtName.Text,
  8. Amount = int.Parse(TxtAmount.Text)
  9. };
  10. Response.Write("Welcome "+TxtName.Text+", Your toal unpaid amount is "+obj.GetTotalAmount().ToString());
  11. }
  12. break;
  13. case "2":
  14. Grade2Customer obj2 = new Grade2Customer()
  15. {
  16. CustomerName = TxtName.Text,
  17. Amount = int.Parse(TxtAmount.Text)
  18. };
  19. Response.Write("Welcome " + TxtName.Text + ", Your toal unpaid amount is " + obj2.GetTotalAmount().ToString());
  20. break;
  21. }
Problem

Changes are the integral part of Software Development and the solution for them is creating a loosely coupled system.

Factory Method Pattern as solution

Let's redefine the Factory Method Pattern in simpler terms.

It says:

This pattern is termed factory because it implements the concept of real-world factories, i.e., creating something. And here are the objects being created:

The Components involved in the Factory Method Pattern are:

Let's start coding,

Step 1

Create a base for concrete products, as in:

  1. public interface IBaseCustomer
  2. {
  3. int Amount { get; set; }
  4. string CustomerName { get; set; }
  5. int GetTotalAmount();
  6. }
Step 2


Derive concrete classes from the above interface:

  1. public class Grade1Customer : IBaseCustomer
Step 3

Create a Base Factory for creating contracts for other factories:
  1. public interface ICustomerBaseFactory
  2. {
  3. IBaseCustomer GetCustomer(int CustomerType);
  4. }

Step 4

  1. public class CustomerFactory : ICustomerBaseFactory
  2. {
  3. public IBaseCustomer GetCustomer(string CustomerType)
  4. {
  5. switch (CustomerType)
  6. {
  7. case "1":
  8. return new Grade1Customer();
  9. case "2":
  10. return new Grade2Customer();
  11. default:
  12. return null;
  13. }
  14. }
  15. }

Step 5

Write Client Code:

  1. protected void BtnCalculate_Click(object sender, EventArgs e)
  2. {
  3. ICustomerBaseFactory objFactory = new CustomerFactory();
  4. IBaseCustomer objCustomer = objFactory.GetCustomer(DdlGrade.SelectedValue);
  5. objCustomer.CustomerName = TxtName.Text;
  6. objCustomer.Amount = int.Parse(TxtAmount.Text);
  7. Response.Write("Welcome " + TxtName.Text + ", Your toal unpaid amount is " + objCustomer.GetTotalAmount().ToString());
  8. }
(Creating separate class library for each component is a good practice)

Now the client code is not directly connected to concrete classes, they go through factories. There is no new keyword in the client code; the client code is easily extended for new customers because adding new customers requires recompilation of the factory, not client code.

Class Diagram

Factory-Method-Pattern-class-diagram.jpg

Conclusion

I had covered the Singleton Patten in my last article about design patterns.

We are done with two creational patterns and now we pretty much understand how Creational design patterns abstract the instantiation process. They help make a system independent of how its objects are created, composed, and represented.

Hope you enjoyed the article, keep reading and comments are always welcome.