Design Pattern – Factory Method

C# CONCEPTS

According to the Gang of Four, the factory method allows the subclass to determine which class object should be created.

Photo by Life Of Pix from Pexels

Learning Objectives

  • What is the factory method design pattern?
  • How to write code using the factory method?

Prerequisites

  • Basic knowledge of OOPS concepts.
  • Any programming language knowledge.

The article demonstrates the factory method using the C# programming language. So, to begin with, C#

View at Medium.com

Getting Started

Let’s consider an example of any Bank with account types as Savings and Current account. Now let’s implement the above example using the factory design pattern

Firstly, create an account type abstract class.

public abstract class AccoutType
{
public string Balance { get; set; }
}

Implement current and saving account classes inheriting the AccountType abstract class as shown below.

https://gist.github.com/ssukhpinder/e7464dadb970cfd779ce05534b3b5ba8

Finally, let’s implement the factory interface, which will provide a contract that helps create a class object. This interface is also known as the Creator.

public interface IAccountFactory
{
AccoutType GetAccoutType(string accountName);
}

At last, write an implementation of the creator interface method as shown below. The class that implements the creator is known as Concrete Creator.

https://gist.github.com/ssukhpinder/83bf043816237f0ce5a7f57aee4e2aa3

That’s it. You have successfully implemented the factory method using the Bank example.


How to use the factory method?

A subclass will decide which “AccountType ” class object will be created based upon the account name.

https://gist.github.com/ssukhpinder/759a61a24d8b63d75892dc41340826a4

For example, if the account name is “SAVINGS,” then the “SavingAccount” class object will be created and returned.

Similarly, if the account name is “CURRENT,” then the “CurrentAccount” class object will be instantiated and returned.

Output

Saving account balance: 10000 Rs
Current account balance: 20000 Rs

Github Repo

View at Medium.com


Thank you for reading, and I hope you liked the article. Please provide your feedback in the comment section.

Follow me on C# Publication, LinkedIn, Instagram, Twitter, Dev.to, Pinterest, Substack, Wix.

Leave a comment