Thursday, February 4, 2010

Factory Method Pattern (Creational)

AIM: Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets classes defer (postpone) instantiate to subclasses.



In simple words, Factory method pattern delegates the work of object creation to derived classes of the interface. This pattern aptly named, as it calls for the use of a specialized object solely to create other object, like a real world factory.




The client is an object that requires an instance of another object (Product) for some purpose. Rather than creating the product instance directly, the client delegates this responsibility to the factory. Once invoked, the factory creates a new instance of the product, passing it back to the client. The factory completely abstracts the creation and initialization of the product from the client. This indirection enables the client to focus on its discrete (isolated) role in the application without concerning how the product created. If the product implementation changes over time, the client remains unchanged.

Class Diagram:





Participants:

  • Product (BankAccount)
    • Defines the interface of objects the factory method creates.
  • ConcreteProduct (ChaseCheckingAccount,ChaseSavingsAccount)
    • Implements the Product interface.
  • Creator/Factory (BankAccountFactory)
    • declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProudct object.
  • ConcreteCreator/Factory (ChaseAccountFactory)
    • Overrides the factory method to return an instance of a ConcreteProduct.

Implementation:


////////////////BankAccount.cs////////////////
using System;
using System.Collections.Generic;
using System.Text;

namespace DesignPatterns.FactoryMethod
{
public abstract class BankAccount
{
public abstract void DepositCash(double depositAmount);
public abstract void DisplayBalance();
public abstract void WithdrawCash(double withdrawAmount);
}
}

////////////////ChaseCheckingAccount.cs////////////////
using System;
using System.Collections.Generic;
using System.Text;

namespace DesignPatterns.FactoryMethod
{
public class ChaseCheckingAccount : BankAccount
{
private double _accountbalance = 0.00;

public ChaseCheckingAccount()
{
Console.WriteLine("CHASE - Checking Account Initialized.");
}

public override void DepositCash(double depositAmount)
{
_accountbalance += depositAmount;
Console.WriteLine("Your money " + depositAmount + " deposited successfully into CHASE checking Account.");
}

public override void DisplayBalance()
{
Console.WriteLine("Your current CHASE Checking account balance is " + _accountbalance);
}

public override void WithdrawCash(double withdrawAmount)
{
if (_accountbalance >= withdrawAmount)
{
_accountbalance -= withdrawAmount;
Console.WriteLine("Your withdrawed " + withdrawAmount + " from CHASE Checking account");
}
else
{
Console.WriteLine("Insufficient funds.");
}
}
}
}

////////////////ChaseSavingsAccount.cs////////////////
using System;
using System.Collections.Generic;
using System.Text;

namespace DesignPatterns.FactoryMethod
{
public class ChaseSavingsAccount : BankAccount
{
private double _accountbalance = 0.00;

public ChaseSavingsAccount()
{
Console.WriteLine("CHASE - Savings Account Initialized.");
}

public override void DepositCash(double depositAmount)
{
_accountbalance += depositAmount;
Console.WriteLine("Your money " + depositAmount + " deposited successfully into CHASE Savings Account.");
}

public override void DisplayBalance()
{
Console.WriteLine("Your current CHASE savings account balance is " + _accountbalance);
}

public override void WithdrawCash(double withdrawAmount)
{
if (_accountbalance >= withdrawAmount)
{
_accountbalance -= withdrawAmount;
Console.WriteLine("Your withdrawed " + withdrawAmount + " from CHASE Savings account");
}
else
{
Console.WriteLine("Insufficient funds.");
}
}


}
}


////////////////BankAccountFactory.cs////////////////
using System;
using System.Collections.Generic;
using System.Text;

namespace DesignPatterns.FactoryMethod
{
public abstract class BankAccountFactory
{
public abstract BankAccount CreateBankAccount(string accountType);

}
}

////////////////ChaseAccountFactory.cs////////////////
using System;
using System.Collections.Generic;
using System.Text;

namespace DesignPatterns.FactoryMethod
{
public class ChaseAccountFactory : BankAccountFactory
{
public override BankAccount CreateBankAccount(string accountType)
{
if (accountType.ToLower() == "savings")
{
return new ChaseSavingsAccount();
}
else
{
return new ChaseCheckingAccount();
}
}
}
}

////////////////FactoryMethodClient.cs////////////////
using System;
using System.Collections.Generic;
using System.Text;

namespace DesignPatterns.FactoryMethod
{
class FactoryMethodClient
{
static void Main(string[] args)
{
BankAccountFactory bankFactory = new ChaseAccountFactory();
BankAccount account = bankFactory.CreateBankAccount("Savings");

account.DepositCash(10000);
account.DisplayBalance();
account.WithdrawCash(2000);
account.DisplayBalance();

Console.ReadLine();
}
}
}

When should use it

Use the Factory Method pattern in any of the following situations:

  • A class can’t anticipate the class of objects it must create.
  • A class wants it subclasses to specify the objects it creates.

In programming language, you can use factory pattern where you have to create an object of any one of sub classes depending on the data provided.


Before You Leave:

  • Tell me wheather you like this article or not? Rate this post accordingly by selecting the stars below.
  • Any suggestion, question or comment? Please post it in the comments below.

0 comments:

Post a Comment