Archive

Posts Tagged ‘Design Patterns’

Strategy Design Pattern in .Net

September 26, 2010 Leave a comment

Strategy design pattern falls under the category of Behavioral Design Pattern. In this pattern, we capture abstraction in an Interface or Abstract class called Strategy Base, and we bury implementation details of algorithms in concrete classes called Concrete Strategy. Client code can then call such different implementation methods based upon some strategy or condition during run time. Client is not tied statically or bound to call fixed methods, rather it can change its strategy dynamically. This is because client never calls any methods directly by instantiating concrete classes. Client sets its strategy via some other class called Context.

Let’s see one such example of this pattern.

StrategyDesignPattern
Fig: Strategy Design Pattern showing all three main components- Strategy Base, Concrete Strategy and Context Classes.

Coming to code, we have:

namespace BehavioralDesignPattern.StrategyDesignPattern
{
public abstract class StrategyBase
{
public abstract long Calculate(int x,int y);
}

public class ConcreteAddStrategy : StrategyBase
{
public override long Calculate(int x, int y)
{
return x + y;
}
}

public class ConcreteSubtractStrategy : StrategyBase
{
public override long Calculate(int x, int y)
{
return x - y;
}
}

public class Context
{
public StrategyBase Strategy { get; set; }
public long CallCalculateMethod(int x, int y)
{
return (Strategy.Calculate(x, y));
}
}
}

We see each of the concrete strategy class implementing algorithm to calculate upon numbers in its own way- one doing addition, while other doing subtraction. But their over all capability to do arithmetic operations upon numbers is abstracted inside Calculate(int, int) method in StrategyBase class.

See the Context class above. It has a property Strategy to get-set of type StrategyBase type. Alternatively, Context class can get-set instance of StrategyBase by a constructor or some method as well like SetStrategy(StrategyBase objSB).

But why do we require this Context class? Because clients agree to call any ConcreteStrategy method not directly. Clients will only hint out for such concrete strategy. What does this mean? This means a lot- Strategy pattern lets you change the guts of an object.

See the client code below:

private void CallStrategyAddMethod()
{
//
Context objCtxt = new Context();
objCtxt.Strategy = new ConcreteAddStrategy();
// Now the object's strategy is to call Add method.
objCtxt.CallCalculateMethod(10, 15);
}

As seen from the above code, object “objCtxt” is able to call method in a concrete strategy class.

Whenever modeling a system after Strategy Design Pattern, one has to carefully think of a way to allow client to convey its strategy to context class.

That’s it.

Template Method Design Pattern in .Net

September 26, 2010 Leave a comment

Template method design pattern falls under the category of Behavioral Design Pattern. In this pattern, a template method defines a skeleton of an algorithm in terms of abstract operations. The template method can contain one or more steps. But these steps will have to be in abstract form only. That said, we cannot change the order of steps, and most importantly we cannot override the template method itself. Only the steps given in the skeleton of algorithm of template method need to be overridden in concrete classes.

Let’s see how classes can be designed in this template pattern.

emplateMethodPattern

Fig: High Level Class Diagram of Template Method Design Pattern

And see the code implementation below:

namespace BehavioralDesignPattern.TemplateMethod
{
public abstract class AbstractAlgorithmSkeleton
{
public void TemplateMethod()
{
// Template Method declaring algorithm
// in terms of abstract operations.
Step1();
Step2();
Step3();
}
public abstract void Step1();
public abstract void Step2();
public abstract void Step3();
}

# region "Concrete Implementations of abstract operations defined in Template Method"
public class ConcreteClassA : AbstractAlgorithmSkeleton
{
public override void Step1()
{
Console.WriteLine("ConcreteClassA, Step 1");
}

public override void Step2()
{
Console.WriteLine("ConcreteClassA, Step 2");
}

public override void Step3()
{
Console.WriteLine("ConcreteClassA, Step 3");
}

public void OtherMethodA()
{
//
}
}

public class ConcreteClassB : AbstractAlgorithmSkeleton
{
public override void Step1()
{
Console.WriteLine("ConcreteClassB, Step 1");
}

public override void Step2()
{
Console.WriteLine("ConcreteClassB, Step 2");
}

public override void Step3()
{
Console.WriteLine("ConcreteClassB, Step 3");
}

public void OtherMethodB()
{
//
}
}

# endregion "Concrete Classes Implementation"
}

We see the concrete classes are overriding the abstract operations defined by the template method in its algorithm. This way template method pattern provides an abstract view of algorithm.

So in practical scenario, this pattern fits only when different types of object instances are required to invoke methods or operations that differ sharply in implementation but the algorithm remaining same. Also, sometimes when are refactoring multiple classes, we can find template method pattern coming into picture.

Consuming the template method:

private void CallTemplateMethod()
{
AbstractAlgorithmSkeleton objTemplate = null;
objTemplate = new ConcreteClassA();
// Now this call to TemplateMethod() will direct calls
// to methods in ConcreteClassA.
objTemplate.TemplateMethod();
}

Important point to note here is: the way we are calling TemplateMethod() of ConcreteClassA from base class AbstractAlgorithmSkeleton reminds us of “The Hollywood Principle”- “Do not call us, we will call for you”. That is, child class method is being called from base class. This way of method call is also known as Inversion of Control.

That’s it.

Decorator Design Pattern in .Net

September 19, 2010 Leave a comment

Decorator design pattern falls under the category of Structural Design Pattern. Structural design pattern emphasizes upon the overall structure of classes and objects in the system either by doing class inheritance or by composing objects into larger structures using object composition. Decorator pattern comes handy when we want to add additional responsibilities to the object during run time.

  • Additional responsibilities can be added statically by class inheritance also. But this will create another problem when we want to add such responsibilities to objects of many classes. We may have to create many child classes to support additional new functions.
  • So instead of creating many child classes of already existing concrete classes, we create a new Decorator, and a new Concrete Decorator class that will add new methods and properties to the existing class object during run time. This way we are not modifying the existing concrete or legacy classes. Responsibilities to objects can be added during runtime because base class of the object and Decorator class share the same base type. And Concrete Decorator class extends the new Decorator.

This design pattern does not come initially during system design. It generally comes during maintenance phase or later in the development phase.

Now let’s see the example of decorator design pattern. We even use mobile phone to send text and multimedia messages. Once the message is sent, the Outbox becomes empty. But sometimes we want to save the sent content message. To do this, we need to select the option of “Send and Save”, and any message sent this way will be saved inside “Sent” folders. Here, even if the user may not always want to save the sent messages, it is for sure that he may definitely want to send messages. Keeping this use case in mind, let’s look into such a class design.

BaseMessage
Fig: Base class for SMS and MMS Concrete Classes

Decorator
Fig: Overall class structure after the introduction of Decorator

From the above diagram, we see two main concrete classes that are involved in sending messages- MobileMMS sends image as message content while MobileSMS send text. Both of the classes are doing well with SendMessage() method. SendMessage() is an abstract method in BaseMessage root class. Decorator, often called DecoratorBase, can be seen inheriting from the same base type of these two MobileMMS and MobileSMS classes, i.e.; inheriting from BaseMessage class. For a Decorator class this is important.

Then, we see MessageProcessor class (often called ConcreteDecorator) which is a concrete implementation of Decorator.

Note: BaseMessage, MobileMMS and MobileSMS are the original classes. Only due to SendAndSave option, a new responsibility SaveMessage() is now required to be added into the objects of MobileMMS and MobileSMS. This is how we see DecoratorBase and ConcreteDecorator need to be added later on.

Now let’s see the actual implementation of the classes.

namespace DecoratorPattern
{
abstract class BaseMessage
{
private string _sender;
private string _recipient;
public string MessageSender
{
get
{
return this._sender;
}
set
{
this._sender = value;
}
}
public string MessageRecipient {
get
{
return this._recipient;
}
set
{
this._recipient = value;
}
}
public abstract void SendMessage();
}
}
namespace DecoratorPattern
{
class MobileSMS: BaseMessage
{
private string _message;
public MobileSMS(string strSender, string strRecipient, string strMessage)
{
this.MessageSender = strSender;
this.MessageRecipient = strRecipient;
this.Message = strMessage;
}
public string Message
{
get
{
return this._message;
}
set
{
this._message = value;
}
}
public override void SendMessage()
{
//Send Text message
}
}
}
namespace DecoratorPattern
{
class MobileMMS:BaseMessage
{
private byte[] image;
public MobileMMS(string strSender, string strRecipient, byte[] image)
{
this.MessageSender = strSender;
this.MessageRecipient = strRecipient;
this.Image = image;
}
public byte[] Image
{
get
{
return this.image;
}
set
{
this.image = value;
}
}
public override void SendMessage()
{
//Send MMS message
}
}
}
namespace DecoratorPattern
{
class Decorator: BaseMessage
{
protected BaseMessage message;
public Decorator(BaseMessage message)
{
this.message = message;
}
public override void SendMessage()
{
message.SendMessage();
}
}
}
namespace DecoratorPattern
{
class MessageProcessor:Decorator
{
public MessageProcessor(BaseMessage message): base(message)
{
}
public void SaveMessage()
{
//Saves outgoing message
}
public override void SendMessage()
{
//
base.SendMessage();
SaveMessage();
}
}
}

Now see the SendSMS and SendMMS methods: how the constructor methods of MessageProcessor are accepting object instances. This is called object composition, and important for Concrete Decorator. This way MessageProcessor will be able to direct the call to the actual method of the class. See the SendMessage() method code above in MessageProcessor.

Client Code

namespace DecoratorPattern
{
class Program
{
public enum SendMessageOption
{
SendOnly = 0,
SendAndSave = 1
}
private void SendSMS(SendMessageOption option)
{
//Send SMS
MobileSMS sms = new MobileSMS("123", "456", "This is example of decorator pattern.");
if (option == SendMessageOption.SendOnly)
{
sms.SendMessage();
}
else if (option == SendMessageOption.SendAndSave)
{
MessageProcessor msgProcessor = new MessageProcessor(sms);
msgProcessor.SendMessage();
}
}
private void SendMMS(SendMessageOption option)
{
//Send MMS
MobileMMS mms = new MobileMMS("123", "456", new byte[] { 1, 2, 3, 4 });
if (option == SendMessageOption.SendOnly)
{
mms.SendMessage();
}
else if (option == SendMessageOption.SendAndSave)
{
MessageProcessor msgProcessor = new MessageProcessor(mms);
msgProcessor.SendMessage();
}
}

static void Main(string[] args)
{
//
Program obj = new Program();
obj.SendSMS(SendMessageOption.SendOnly);
obj.SendSMS(SendMessageOption.SendAndSave);
obj.SendMMS(SendMessageOption.SendOnly);
obj.SendMMS(SendMessageOption.SendAndSave);
//Wait for user enter key
Console.Read();
}
}
}

Hope the Decorator design pattern is now simple enough to understand.

Designing Business Logic Layer: Some Guidelines

Business Logic Layer is a very crucial layer for any data base applications. A timely thought when applied to this layer from the beginning of application layers design can save lots of time and complexity. Software architects divide the software into modules, then different layers, and core functioning layers for important application features. But when actual development work starts, complexity of different layers and modules start crawling into code gradually.
Reason being:
• We try to mix business rules of different modules wishfully
• Writing methods with abundant codes
• Not clearly separating responsibilities of presentation and data access layers
• Creating code duplicity, i.e.; writing same set of code or methods at various places

Results are:
• Difficult to debug
• Difficult to understand the flow
• Difficult to maintain and modify business rules correctly when such rules exist across layers and modules
• Difficult to write Unit Tests

We can avoid these things if we take care of these things when writing codes.
• Write methods that do single meaningful task with one call. Do not mix other code logic with the methods. For example, if we write SavePayment() method, then this method should only focus on save task, and not update or delete or check connection status or read Xml files, etc. This is what we call Single Responsibility Principle.
• Encourage use of factory methods for object creation instead of writing lots of If-else constructs based upon some input type values.
• When you need data or result sets (DTO) of other modules, then preferably call business logic layer methods of that module instead of writing that module code logic into yours. This is quite important aspect for any business logic layer.
• Classes in this layer should be loosely coupled. For this different injection patterns like dependency injection or inversion of control, etc can help. Sometimes even a simple Enum type can come to a great rescue.
• Write business methods that accept valid entity class object or DTO object in business rather than single valued parameters like integer or string or array or even optional params. This ensures business logic layer code function even unmodified when there are database table and entity or DTO class changes in behind.
• Avoid lots of business rules in stored procedures or even in presentation UI.
• Business logic layer methods should not be aware of presentation UI controls’ properties or values. These methods should accept values in integer or string instead.

Let me explain all these points by one example. I worked in an accounting module of a project where customers can make payments of their bills in various ways. They can make either full payment or in-partial or even in installments. For each payment mode, there were different rules and validations. So this module had clear separation of implementation with rules of each mode functioning without depending upon others. This way our lots of coding and debugging time got saved.
Let’s see the code snippets.

Enum showing different Payment Mode

public enum PaymentMode

{
Normal,
Part,
Installment
}

Custome Bill DTO

public class CustomerBillDTO

{
private Int64 intBillNo;
private Int16 intBillMonth;
private Int16 intBillYear;
private double dblBillAmount;
private string strCustomerID;
private Int64 intPayAmount;
//And many other fields…
}

Payment Processor factory class

interface IPaymentProcessorFactory
{
//
IPaymentProcessor GetPaymentProcessor(PaymentMode mode);
}

public class PaymentProcessorFactory : IPaymentProcessorFactory
{
//
private IPaymentProcessor objPaymentProcessor = null;

public IPaymentProcessor GetPaymentProcessor(PaymentMode mode)
{
//
switch (mode)
{
case PaymentMode.Normal:
objPaymentProcessor = new NormalPaymentProcessor();
break;

case PaymentMode.Part:
objPaymentProcessor = new PartPaymentProcessor();
break;
case PaymentMode.Installment:
objPaymentProcessor = new InstallmentPaymentProcessor();
break;
}
return objPaymentProcessor;
}
}

Different Payment Processor class

public interface IPaymentProcessor

{
//
bool SavePayment(CustomerBillDTO Bill);
}

public class NormalPaymentProcessor:IPaymentProcessor
{
//
public bool SavePayment(CustomerBillDTO Bill)
{
return true;
}
}

public class PartPaymentProcessor : IPaymentProcessor
{
//
public bool SavePayment(CustomerBillDTO Bill)
{
return true;
}
}

public class InstallmentPaymentProcessor : IPaymentProcessor
{
//
public bool SavePayment(CustomerBillDTO Bill)
{
return true;
}
}

Main class that processes each payment

class PaymentProcess

{
private IPaymentProcessorFactory objProcessor = null;
public PaymentProcess(IPaymentProcessorFactory Processor)
{
//
this.objProcessor = Processor;
}

public bool ProcessPayment(CustomerBillDTO Bill, PaymentMode mode)
{
//
IPaymentProcessor objPaymentProcessor = this.objProcessor.GetPaymentProcessor(mode);
return objPaymentProcessor.SavePayment(Bill);
}
}

At the calling end, we simply make a generous call as:

private void BtnSave_Click(object sender, EventArgs e)
{
//
PaymentProcessorFactory objFactory = new PaymentProcessorFactory();
PaymentProcess objProcess = new PaymentProcess(objFactory);
bool result = objProcess.ProcessPayment(objCustomerBillDTO(), PaymentMode.Normal);
}

As we see this is how we have clearly separated each logical functioning of a SavePayment() method.
Even in future, if Part or Installment payment mode is stopped, we do not have to modify the code logic to add any If-else construct to branch out or skip any code flows. In case a new payment mode is added, then writing a new XModePaymenetProcessor class, adding one more Enum value and finally one more object instantiation code in factory class will do enough.

Adding or removing any Bill or Customer related fields in CustomerBillDTO do not even pose threat to this business logic layer.

Finally, one should always keep in mind that you write class and class methods for others. So you should be very clear here: what the class should offer and how.

Thanks.