Tallan Blog

Tallan’s Experts Share Their Knowledge on Technology, Trends and Solutions to Business Challenges

Design Patterns – Factory Method

The Factory Method design pattern is a creational pattern for simplifying construction of similar objects through means of subclasses and a superclass or interface/class relationships. Makes perfect sense right?  Alright, more simply it helps reduce the complexity of your code when it comes to creating similar objects and taking action with them.

So… where is this pattern helpful?  For the sake of this post, imagine you run a popular website where users can come to get rewards for activities or purchases they have made, and that your site currently only lets users receive payouts from PayPal. More than likely the application will have a lot of code written with only PayPal in mind, scattered throughout the code base with conditional behaviors at every step of the way. Now, let’s imagine that times are changing and your users would rather be paid out with Amazon Credit or Venmo. What do you do? Do you complicate the logic further by adding more conditions at each step of the process thereby making your application less testable and more likely prone to error?

No, you don’t, well I really hope you would say no.

Let’s fix our payout application by means of the Factory Method pattern. We will abstract away the implementation of payments, so our existing PayPal payout code will be relocated to a new class PayPalPayout, which will implement our new interface IPayout. We will also need to create VenmoPayout and AmazonPayout.

FactoryPatternExampleClassDiagram

For the sake of this simple explanation we only have two items in our interface, the value of the payout, and then the method “pay”, and then our implementations also have those.  So now we know that if we have an IPayout, then we can access the value and call the method pay, and importantly, we don’t really care how these items are handled, it is just about their availability.

Now we can use a factory to create an implementation of a payout to be consumed by our application.  Let’s take a look at some basic code and see a really simple example at work.

Below see the interface IPayout and then the three implementations: VenmoPayout, AmazonPayout, and PaypalPayout.

interface IPayout
{
	int Value { get; set; }
	void Pay();
}

class VenmoPayout : IPayout
{
	public int Value { get; set; }
	public void Pay()
	{
		// do some sort of logic connecting to Venmo and paying
		Console.WriteLine($'Payed ${Value} with Venmo');
	}
}
class AmazonPayout : IPayout
{
	public int Value { get; set; }
	public void Pay()
	{
		// do some sort of logic connecting to Amazon and paying
		Console.WriteLine($'Payed ${Value} with Amazon');
	}
}
class PaypalPayout : IPayout
{
	public int Value { get; set; }
	public void Pay()
	{
		// do some sort of logic connecting to PayPal and paying
		Console.WriteLine($'Payed ${Value} with Paypal');
	}
}

*Note about the code snippets, the single quotes were regular quotes in the actual c# code, but were not behaving well here, so if you want to copy this code and run it, you will need to replace the ‘ with “

Now below we have our static payout factory which simply takes the type and constructs the matching type and returns.

static class PayoutFactory
{
    public static IPayout GeneratePayout(string type)
    {
        IPayout payout = null;
        switch (type)
        {
            case '1':
                payout = new PaypalPayout();
                break;
            case '2':
                payout = new VenmoPayout();
                break;
            case '3':
                payout = new AmazonPayout();
                break;
        }
        return payout;
    }
}

Finally we have the main method which just prompts the user for their desired payout, feeds that to the factory, then asks the user for the value, and finally completes the payout. Note line 11, 15, and 16 are highlighted, this is to point out the factory method instantiating the payout and then actions being taken on the payout.

static void Main(string[] args)
{
	StringBuilder sb = new StringBuilder()
		.AppendLine('What type of payout do you want?')
		.AppendLine('\t 1. PayPal')
		.AppendLine('\t 2. Venmo')
		.AppendLine('\t 3. Amazon Credit');
	Console.WriteLine(sb.ToString());

	var paymentType = Console.ReadLine();
	var payout = PayoutFactory.GeneratePayout(paymentType);
	if(payout != null)
	{
		Console.WriteLine('How much money do you want?');
		payout.Value = int.Parse(Console.ReadLine());
		payout.Pay();
	}
	Console.Read();
}

If we execute this code, we can see that it no matter which payment type we choose, the payment executes.


What type of payout do you want?
	1. Paypal
	2. Venmo
	3. Amazon Credit
1
How much money do you want?
25
Payed $25 with Paypal

What type of payout do you want?
	1. Paypal
	2. Venmo
	3. Amazon Credit
2
How much money do you want?
100
Payed $100 with Venmo

What type of payout do you want?
	1. Paypal
	2. Venmo
	3. Amazon Credit
3
How much money do you want?
1000
Payed $1000 with Amazon

 

So, what are the key takeaways from this?

  1. The Factory Method pattern can be used to simplify creation of similar items without having to explicitly specify the class of the object.
  2. Using the Factory Method pattern can help make code flexible and follow the single responsibility principle.
  3. Using the Factory Method pattern will help your application follow the open/closed principle for which it will be significantly easier to extend you application without necessarily modifying the source code.

Click Here to learn more about Tallan or see us in person at one of many Events!

Share this post:

No comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

\\\