Factory Pattern

I had to use Factory pattern for one my mutual fund house project.The investment strategies includes buying funds as Lumpsum,SIP etc..and the funds which has be bought have options like Redeem,Purchase,Switch.This might not sound familiar if you are not from banking and finance domain,you can have a read over here.

Intention :

There are various Investment plans like SIP,LumpSum etc..and all investment plans has the following option (Purchase,Redeem,Switch).So Its clear that i would have an interface and classes below


public interface IFundOption

{

void Purchase();

void Redeem();

void Switch();

}

//Investment Plan

class Luupsum: IFundOption

{

public void Purchase()

{

//Do Purchase

}

public void Redeem()

{

//Do Redeem

}

public void Switch()

{

//Do Switch

}

}

class SIP : IFundOption

{

public void Purchase()

{

//Do Purchase

}

public void Redeem()

{

//Do Redeem

}

public void Switch()

{

//Do Switch

}

}

 

Problem  :

Given an investment plan as argument,i want to get the instance of investment plan and perform the various options like redeem,purchase etc..Typically i don’t want to write a switch case where i make a comparison based on investment plan and then initiate the class(against open closed principle). The goal is to write a method which accepts investment plan name and returns the instance of investment plan.


public investmentplaninstance   GetinstanceofInvesmentPlan(string investementplanname)

{

return investmentplaninstance ;// goal

}

This is where Factory Pattern comes in,You create a interface for creating object and let sub classes decide which class to initiate.

Factory Pattern :

1.Lets create a interface which is responsible for returning investmentplaninstance.


public interface IGetInvestmentPlanInstance

{

IFundOption CreateInvestmentPlanInstance(); //the instance should be used to create investment plan.

}

2. Lets create Managers (sub classes) which creates the instance of investment plan.


class SIPManager : IGetInvestmentPlanInstance

{

public IFundOption CreateInvestmentPlanInstance()

{

var sipinstance = new SIP(); //sip class implements IFundOption  interface.

return sipinstance;

}

}

class LumpsumManager : IGetInvestmentPlanInstance

{

public IFundOption CreateInvestmentPlanInstance()

{

var lumsuminstance = new Lumpsum(); //Lumpsum class implements IFundOption  interface.

return lumsuminstance ;

}

}

 

3. We have the managers who are ready to give the investment plan instance based on investment plan name.Typically we would put all manager class in settings file/config,and based on input,we create the manager instance based on reflection .


static IGetInvestmentPlanInstance GetManagerClass(string investmetpan)

{

var getmanager = _dictionary.Key(investmentplan);

return Assembly.GetExecutingAssembly.CreateInstance(getmanager) as IGetInvestmentPlanInstance ;

}

[/csharp]

we would make use of this manager class and get the instance of investment plan as below,



var getmanager = GetManagerClass("SIPManager ");

IFundOption options = getmanager.CreateInvestmentPlanInstance();

options.Purchase();

options.Redeem();

 

 

 

#50-SOLID -Liskov Substitution Principle

Liskov Substitution Principle: SubType (Child Class)Must be Substitutable For Base Type(Base Class).

LSP comes into use when you use inheritance/Abstraction.

Rules:

1.Child Class Should not remove Base Class Behaviour.

2.Child Class Should not violate base class invariants.

In short,the Calling code should not know whether it is calling the base class or derived class.

#3 Decorator Pattern

When to Use Decorator Pattern?

Add New Responsibility(functionality) to the class,without breaking the existing functionality.

Usage:

1.Component as abstract class/Interface.

2.Concrete Components Implementing the Components.

3.Decorator as abstract class/Interface with Component as member initialized via constructor.

4.Concrete Decorator Implements Decorator.

Consequence:
Functionality are added at runtime,Hard to debug(Since object implements both Concrete Component and Concrete Decorator).

 Source Code:https://github.com/rangesh-/Design-Patterns/tree/master/Design%20Patterns/Decorartor%20Pattern

State Pattern

When to Use State Pattern?

Lets Assume a Case where we design a CardReader System.The specification of  the CardReader would be something like at a given point of time the machine can either insert or discard or hold the card for processing.so we find the Usage of State in CardReader .

State of CardReader:

Hold,Discard,Insert

Normal Approach:

A Normal Approach would be to have an Enum with specific state and traditional switch case performing various task of the CardReader.

Code:

public enum CardReaderState
{
Insert,
Discard,
Hold

}
class CardReader
{
private CardReaderState state=CardReaderState.Insert;
public void PerformCardOperation()
{
switch (state)
{
case CardReaderState.Discard:
IdleState();

break;
case CardReaderState.Insert:
state = CardReaderState.Hold;
InsertCard();

break;
case CardReaderState.Hold:
state = CardReaderState.Discard;
CardTasks();
break;
}

}

private void CardTasks()
{
Console.WriteLine(“CardReader Holding the Card For Processing”);
PerformCardOperation();
}

private void IdleState()
{
Console.WriteLine(“CardReader is Idle”);
}

private void InsertCard()
{
Console.WriteLine(“Card Inserted”);
PerformCardOperation();

}
}

Problem with the Above Code:It Solves the Problem,but it clearly fails against Open/Closed Principles and lacks oo principles.what if we need another state introduced,we must modify the enum and alter the switch cases.An addition might introduce new bug and break the functionality.

Solution:

The State Pattern Comes to the rescue.

Definition:Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

My Definition:

1.Create a abstract Class which every state must perform.

2.Override the State behavior with corresponding states.

3.Chain the Next State in the Respective State.

Step 1:

1,Abstract Class :

public abstract class CardState
{
protected CardReader _reader; 

public virtual void PerformCardOperation()
{

}
}

2.State Class for every states

public class CardInsert : CardState
{

public CardInsert(CardReader Reader)
{
_reader = Reader;
}

public override void PerformCardOperation()
{
Console.WriteLine(“Card Inserted”);
_reader.CurrenState=new CardHold(_reader);//Chaining the next States
}

}

public class CardHold : CardState

{
public CardHold(CardReader reader)
{
_reader = reader;
}
public override void PerformCardOperation()
{
Console.WriteLine(“Card Holded For Performing Operation”);
_reader.CurrenState=new CardDiscard(_reader);//Chaining the next state

}

}

public class CardDiscard : CardState
{
public CardDiscard(CardReader reader)
{
_reader = reader;
}
public override void PerformCardOperation()
{
Console.WriteLine(“Card discarded”);
}
}

3.Chain the Respective State : 

In the above code this is the line

_reader.CurrenState=new CardHold(_reader);

which does the chaining the next state.i.e from insert to hold and then to Discard.