Showing posts with label Architecture and Design Pattern. Show all posts
Showing posts with label Architecture and Design Pattern. Show all posts

07 December, 2012

Iterator Design Pattern


Iterator pattern is a design pattern which is used to traverse aggregate object often called container and access container’s object without exposing it’s underlying representation. Iterator pattern decoupled algorithm from aggregate object or container. In some cases, algorithms are container specific. We often use collection in C# and then we traverse the collection without knowing it’s internal details. Collection is grouping of some object. Objects can be same type or different type. Collection in fact actively used iterator pattern. 

 
The above figure is UML class diagram for Iterator Pattern. The main idea behind the iterator pattern is to take the responsibility of traversing container and put it to the iterator object. The iterator object will maintain the state of the iteration, keeping track of the current item and track for the next item to iterate.

Benefits:
1.       Access element of container without exposing it’s internal details.
2.       Provides a uniform interface for traversing different collection (aggregate object).
3.       Provides multiple simultaneous traversals in a collection.

Implementation:
Let’s come to the point. We are going to implement iterator design pattern. I am using here a collection for fruits item. The main actor in here:

IIterator – Interface to define Iterator (Concrete iterator class)
Iterator – Concrete iterator class which is used to iterate elements.
ICollection – Interface to define aggregate.
Collection – Concrete aggregate class.

I used FruitItem class as item class here.

Step 1: Create Item class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IteratorPattern
{
    /// 
    /// Item class
    /// 
    public class FruitItem
    {
        public string Id { get; set; }
        public string Name { get; set; }

    }

}

Step 2: Create IIterator Interface
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IteratorPattern
{
    /// 
    /// Interface for Iterator
    /// 
    public interface IIterator
    {
        FruitItem First();
        FruitItem Next();
        FruitItem CurrentItem { get; }
        bool IsDone { get; }
    }
}

Step 3: Create concrete Iterator class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IteratorPattern
{
    /// 
    /// Concrete Iterator Class
    /// 
    public class Iterator : IIterator
    {

        private Collection collection;
        private int current = 0;
        private int step = 1;

        public Iterator(Collection vCollection)
        {

            this.collection = vCollection;

        }

        public FruitItem First()
        {
            current = 0;
            return (FruitItem)collection[current];
        }

        public FruitItem Next()
        {
            current ++;

            if (!IsDone)
                return (FruitItem)collection[current];
            else
                return null;
        }


        public bool IsDone
        {
            get { return current >= collection.Count; }
        }


        public FruitItem CurrentItem
        {
            get { return (FruitItem) collection[current]; }
        }

        // Gets or sets stepsize
        public int Step
        {
            get { return step; }
            set { step = value; }

        }


    }
}


Step 4: Create collection interface.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IteratorPattern
{
    /// 
    /// Interface for Aggregate class
    /// 
    public interface ICollection
    {
        Iterator CreateIterator();
    }
}

Step 5: Create concrete collection class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace IteratorPattern
{
    /// 
    /// Concrete aggregate class
    /// 
    
    public class Collection : ICollection
    {
        private ArrayList lstFoodItem = new ArrayList();

        public Iterator CreateIterator()
        {
            return new Iterator(this);
        }


        // Get counted items
        public int Count
        {
            get 
            { 
                return lstFoodItem.Count;
            }

        }



        // Indexer

        public object this[int index]
        {

            get { return lstFoodItem[index]; }

            set { lstFoodItem.Add(value); }

        }
    }
}


Step 6: Create client class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IteratorPattern
{
    class Program
    {
        public static void Main(string[] args)
        {
            Collection collection = new Collection();

            collection[0] = new FruitItem() { Id = "1", Name = "Mango" };
            collection[1] = new FruitItem() { Id = "2", Name = "Orange" };
            collection[2] = new FruitItem() { Id = "3", Name = "Banana" };
            collection[3] = new FruitItem() { Id = "4", Name = "Apple" };
            collection[4] = new FruitItem() { Id = "5", Name = "Lichi" };
            collection[5] = new FruitItem() { Id = "7", Name = "Tamarind" };


            // Create iterator
            Iterator iterator = new Iterator(collection);
            Console.WriteLine("Items by iterating over collection");

            for (FruitItem item = iterator.First(); !iterator.IsDone; item = iterator.Next())
            {
                Console.WriteLine(item.Name);
            }

            Console.ReadLine();
        }
    }
}

Output:

09 August, 2012

Strategy Design Pattern


Strategy design pattern is a behavioral design pattern. It is a particular software design pattern where algorithms are selected at runtime.

According to the book of Design Pattern (Gang of Four) - “Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. “

The key phrases of definition are "Family of algorithms", "encapsulate", and "interchangeable". Actually, Strategy Pattern encapsulates a collection of functions that do similar yet not identical jobs. Client is not bound to call fixed methods; rather it can change its strategy dynamically at run time. Client don’t call any methods directly by instantiating concrete classes. It sets its strategy via context class.

There are three main parts in strategy pattern:

1.       Strategy – An interface that defines how the algorithm will be called.
2.       Concrete Strategy – The implementation of the strategy.
3.       Context – It holds the concrete strategy.

 


Implementation:
Suppose you have two lists of items. Item here integer numbers. Now, if you want to search an item from either of the lists. You can use either one of the algorithms from Linear Search or Binary search. Since binary search algorithm cannot search data without sorted list, we take here a sorted list. Now the strategy of client to use which one – Binary search or linear search. Let’s implement the problem by strategy pattern using c#.


Step 1: Create an Interface for Strategy

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StrategyPattern
{
    /// 
    /// Strategy defines how algorithm will be called
    /// 
    public interface ISearchStrategy
    {
        int Search(int[] list, int item);
    }
}


Step 2: Create concrete strategy (Linear Search)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StrategyPattern
{
    /// 
    /// Concrete strategy(Linear Search Algorithm)
    /// 
    public class LinearSearch : ISearchStrategy
    {
        #region ISearchStrategy Members

        public int Search(int[] list, int item)
        {
            Console.WriteLine("Linear Search");
            int position = 0;

            for (int i = 0; i < list.Count(); i++)
            {
                if (list[i] == item)
                {
                    position = i;
                    break;
                }
            }

            return position;
        }

        #endregion
    }
}

Step 3: Create concrete strategy (Binary Search)

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StrategyPattern
{
    /// 
    /// Concrete strategy(Binary Search Algorithm)
    /// 
    public class BinarySearch : ISearchStrategy
    {
        #region ISearchStrategy Members

        public int Search(int[] list, int item)
        {
            Console.WriteLine("Binary Search");

            int beg = 0;
            int end = list.Count() - 1;
            int mid = (int)((beg + end)/2);
            int position = 0;

            while (beg <= end && list[mid] != item)
            {
                if(item < list[mid])
                    end = mid - 1;
                else
                    beg = mid + 1;

                mid = (int)((beg + end)/2);
            }

            if (list[mid] == item)
                position = mid;
            else
                position = 0;


            return position;
        }

        #endregion
    }
}

 
Step 4: Create a context class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StrategyPattern
{
    /// 
    /// Concrete strategy(Linear Search Algorithm)
    /// 
    public class LinearSearch : ISearchStrategy
    {
        #region ISearchStrategy Members

        public int Search(int[] list, int item)
        {
            Console.WriteLine("Linear Search");
            int position = 0;

            for (int i = 0; i < list.Count(); i++)
            {
                if (list[i] == item)
                {
                    position = i;
                    break;
                }
            }

            return position;
        }

        #endregion
    }
}


Step 5: Client class to demonstrate strategy pattern

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StrategyPattern
{
    /// 
    /// Client class
    /// 
    class Program
    {
        static void Main(string[] args)
        {

            int[] sortedList = { 1, 2, 3, 4, 5, 6, 7, 8 };

            //Instance of context to follow different strategies
            SearchList objSearchList = new SearchList();

            objSearchList.SetSearchStrategy(new BinarySearch());
            objSearchList.Search(sortedList, 4);

            objSearchList.SetSearchStrategy(new LinearSearch());
            objSearchList.Search(sortedList, 7);

            Console.ReadLine();
        }
    }
}


Output:

08 August, 2012

Decorator Design Pattern


You who work on design pattern must familiar with Gang of Four (GoF). Design Patterns: Elements of Reusable Object-Oriented Software is a Software Engineering book. The authors of this book are Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides. The authors of this book are often refers to as Gang of Four (GoF).  It’s a parody relating to Mao’s Gang of Four. This book describes the recurring solution of common problem in software design. The Gang of Four (GoF) patterns are generally considered the foundation for all other patterns. They are categorized in three groups: Creational, Structural, and Behavioral. Factory Pattern, Abstract Factory Pattern, Singleton Pattern, Builder e.t.c are creational design pattern. Decorator, Adapter, Bridge, Façade, Proxy, Composite e.t.c are structural design pattern. Command, interpreter, strategy, iterator e.t.c are behavioral design pattern.

Decorator Design Pattern
Decorator Design Pattern is a structural design pattern. It is also known as wrapper. It is used to add additional functionality to a particular object during run time without affecting other objects. Responsibility can be adding or removing at run time. Critics says that it uses lot of little object of similar type.

Let’s consider a scenario in which I am going to implement Decorated Design Pattern. We, Bangladeshi are very much cricket loving. A cricket equipment shop declared some package on the occasion of Cricket World Cup 2011. The base package is with a bat and a ball and its cost is 1500 Taka (Bangladeshi Currency). The smart package is with a bat, a ball and 6 stamps i.e base package plus 6 stamps and its cost is 1500 + 600 = 2100 Taka. The special package is with a bat, a ball, 6 stamps and a pair of gloves i.e smart package plus a pair of gloves. It’s cost is 2100 + 500 = 2600 Taka. It looks like the following figure. Actually, the top one wrapped the inner packages.


 

Before going to implement the scenario by decorated design pattern, I would like to show you the class diagram. The class diagram is given below.



 

Implementation: Let’s implement decorated design pattern by C#.

Step 1: Create interface ICricketInstrument for all package of cricket instrument.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
    /// 
    /// Interface for Cricket Instrument
    /// Developed by: Mahedee
    /// 
    public interface ICricketInstrument
    {
        double Cost { get; }
        string Insturments { get; }
    }
}


Step 2: Create a base type for Concrete Cricket Instrument Package and Instrument Package Option
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
    /// 
    /// Base type for concrete cricket instrument package and decorator(option).
    /// Developed by: Mahedee
    /// 
    public abstract class CricketInstrument : ICricketInstrument
    {
        private double cost = 00;
        private string instrument = "Cricket Instruments: ";

        #region ICricketInstrument Members

        public virtual double Cost
        {
            get { return cost; }
        }

        public virtual string Insturments
        {
            get { return instrument; }
        }

        #endregion
    }
}


Step 3: Create a base type for Concrete Cricket Instrument Package Option. It is actually decorator – to decorate Instrument package.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
    /// 
    /// Base type or decorator for concrete cricket instrument package.
    /// Developed by: Mahedee
    /// 
    public abstract class CricketInstrument : ICricketInstrument
    {
        private double cost = 00;
        private string instrument = "Cricket Instruments: ";

        #region ICricketInstrument Members

        public virtual double Cost
        {
            get { return cost; }
        }

        public virtual string Insturments
        {
            get { return instrument; }
        }

        #endregion
    }
}


Step 4: Create base package of Cricket Instrument.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
    /// 
    /// Base Cricket Insturment Package
    /// 
    public class BasePackage : CricketInstrument
    {
        double cost = 1500;
        string instruments = "Ball and Bat";

        public override double Cost
        {
            get { return cost; }
        }

        public override string Insturments
        {
            get { return base.Insturments + instruments; }
        }

    }
}


Step 5: Decorate Smart package for Cricket Instrument
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
    /// 
    /// Smart Package = Base Package (Bat, Ball) + 6 Stamps
    /// Developed by: Mahedee
    /// 
    public class SmartPackage : PackageOption
    {
        double cost = 600;
        string instruments = "6 Stamps";
        CricketInstrument objCricketInstrument;

        public SmartPackage(CricketInstrument objPCricketInstrument)
        {
            objCricketInstrument = objPCricketInstrument;
        }

        public override double Cost
        {
            get { return objCricketInstrument.Cost + cost; }
        }

        public override string Insturments
        {
            get { return objCricketInstrument.Insturments + ", " + instruments; }
        }
    }
}


Step 6: Decorate Special Package for Cricket Instrument.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
    /// 
    /// Special Package = Base Package (Bat, Ball) + 6 Stamps + 1 Pair - Gloves
    /// Developed by: Mahedee
    /// 
    public class SpecialPackage : PackageOption
    {
        double cost = 500;
        string instruments = "Gloves - 1 Pair";
        CricketInstrument objCricketInstrument;

        public SpecialPackage(CricketInstrument objPCricketInstrument)
        {
            objCricketInstrument = objPCricketInstrument;
        }

        public override double Cost
        {
            get { return objCricketInstrument.Cost + cost; }
        }

        public override string Insturments
        {
            get { return objCricketInstrument.Insturments + ", " + instruments; }
        }

    }
}



Step 7: Program class to create base package and decorate other package with option.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DecoratorPattern
{
    public class Program
    {
        static void Main(string[] args)
        {
            //Base Insturment class

            CricketInstrument objCricketInstruments = new BasePackage();
            Console.WriteLine("::Base Package::");
            Console.WriteLine(objCricketInstruments.Insturments);
            Console.WriteLine("Instrument's Cost: " + objCricketInstruments.Cost);

            Console.WriteLine();

            //Smart Package
            objCricketInstruments = new SmartPackage(objCricketInstruments);
            Console.WriteLine("::Smart Package::");
            Console.WriteLine(objCricketInstruments.Insturments);
            Console.WriteLine("Instrument's Cost: " + objCricketInstruments.Cost);

            Console.WriteLine();

            //Special Package
            objCricketInstruments = new SpecialPackage(objCricketInstruments);
            Console.WriteLine("::Special Package::");
            Console.WriteLine(objCricketInstruments.Insturments);
            Console.WriteLine("Instrument's Cost: " + objCricketInstruments.Cost);

            Console.ReadLine();


        }
    }
}

04 August, 2012

Abstract Factory Pattern

Abstract factory pattern is a creational design pattern. Creational design pattern is deals with object creation mechanism. Object creation mechanism is changed on the basis of problem. Abstract factory pattern provides an interface to create families of related or dependent objects without specifying their concrete class. It is identified on the basis of problem complexity. It is encapsulated the process of instantiation of family of classes. Abstract factory pattern is widely used in framework and libraries to encapsulate the family of classes.

Elements of Abstract Factory Pattern:
1.       Abstract Factory – An Interface to create families of related or dependent item object.
2.       Concrete Factory – Implement the interface to create families of related item object.
3.       Abstract Item – An interface to create concrete item object.
4.       Concrete Item – Implement the interface to create concrete item object.
5.       Client – Uses Interface (abstract Item) provided by abstract factory and access concrete object by this interface.

Implementation:
Here I implemented abstract factory pattern in International Cricket Team by C#. The UML diagram is given below.



Step 1:  Create interface for Item class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{
    /// 
    /// Interface for Item class
    /// 
    
    public interface ICricketer
    {
        string BattingStrength();
        string BowlingStrength();
        string AllroundingStrength();
        string IconPlayer();
    }
}



Step 2: Create Factory Interface
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{
    /// 
    /// A Factory interface
    /// 
    public interface ICricketerFactory
    {
        ICricketer GetCricketer(CricketerBase cricketerBase); 
    }
}


Step 3: Define the type of Base object
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

    /// 
    /// Define the type of Base Object
    /// 
    public enum CricketerBase
    {
        AustralianCricketer,
        BangladeshiCricketer,
        EnglishCricketer,
        IndianCricketer,
        PakistaniCricketer
    }

}



Step 4: Create Concrete factory class for Asian Cricketer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

    /// 
    /// Concrete factory class for Asian Cricketer
    /// 
    
    public class AsianCricketerFactory : ICricketerFactory
    {

        #region ICricketerFactory Members

        public ICricketer GetCricketer(CricketerBase cricketerBase)
        {
            ICricketer objICricketer = null;

            switch (cricketerBase)
            {
                case CricketerBase.BangladeshiCricketer:
                    objICricketer = new BangladeshiCricketer();
                    break;
                case CricketerBase.IndianCricketer:
                    objICricketer = new IndianCricketer();
                    break;
                default:
                    break;
            }
            return objICricketer;
        }

        #endregion
    }
}


Step 5: Create Concrete factory class for European Cricketer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{
    /// 
    /// Concrete factory class for European Cricketer
    /// 
    
    public class EuropeanCricketerFactory : ICricketerFactory
    {

        #region ICricketerFactory Members

        public ICricketer GetCricketer(CricketerBase cricketerBase)
        {
            ICricketer objICricketer = null;

            switch (cricketerBase)
            {
                case CricketerBase.EnglishCricketer:
                    objICricketer = new EnglishCricketer();
                    break;
                default:
                    break;
            }
            return objICricketer;
        }

        #endregion
    }
}


Step 6: Create Item class for Bangladeshi Cricketer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

    /// 
    /// Item class for Bangladeshi Cricketer
    /// 
    
    public class BangladeshiCricketer : ICricketer
    {
        #region ICricketer Members

        public string BattingStrength()
        {
            return "60%";
        }

        public string BowlingStrength()
        {
            return "70%";
        }

        public string AllroundingStrength()
        {
            return "85%";
        }

        public string IconPlayer()
        {
            return "Shakib Al Hasan";
        }

        #endregion
    }
}


Step 7: Create Item Class for Indian Cricketer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

    /// 
    /// Item class for Indian Cricketer
    /// 
    
    public class IndianCricketer : ICricketer
    {

        #region ICricketer Members

        public string BattingStrength()
        {
            return "85%";
        }

        public string BowlingStrength()
        {
            return "60%";
        }

        public string AllroundingStrength()
        {
            return "70%";
        }

        public string IconPlayer()
        {
            return "Shachin Tendulkar.";
        }

        #endregion
    }
}


Step 8: Create Item class for Pakistani Cricketer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

    /// 
    /// Item class for Pakistani Cricketer
    /// 
    
    public class PakistaniCricketer : ICricketer
    {

        #region ICricketer Members

        public string BattingStrength()
        {
            return "75%";
        }

        public string BowlingStrength()
        {
            return "85%";
        }

        public string AllroundingStrength()
        {
            return "75%";
        }

        public string IconPlayer()
        {
            return "Shahid Afridi.";
        }

        #endregion
    }
}


Step 9: Create Item class for English Cricketer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

    /// 
    /// Item class for English Cricketer
    /// 
   
    public class EnglishCricketer : ICricketer
    {

        #region ICricketer Members

        public string BattingStrength()
        {
            return "75%";
        }

        public string BowlingStrength()
        {
            return "80%";
        }

        public string AllroundingStrength()
        {
            return "70%";
        }

        public string IconPlayer()
        {
            return "Kavin Pietersen";
        }

        #endregion
    }
}


Step 10: Create a client class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AFP
{

    /// 
    /// Client Class
    /// 
    
    class Program
    {
        static void Main(string[] args)
        {
            AsianCricketerFactory objAsianFactory = new AsianCricketerFactory();
            ICricketer objIAsianCricketer = objAsianFactory.GetCricketer(CricketerBase.BangladeshiCricketer);
            Console.WriteLine("Bangladesh Cricket Team\nBatting Strength:" + objIAsianCricketer.BattingStrength());
            Console.WriteLine("Bowling Strength:" + objIAsianCricketer.BowlingStrength());
            Console.WriteLine("Allrounding Strength:" + objIAsianCricketer.AllroundingStrength());
            Console.WriteLine("Icon Player:" + objIAsianCricketer.IconPlayer());

            Console.WriteLine();

            EuropeanCricketerFactory objEuropeanFactory = new EuropeanCricketerFactory();
            ICricketer objIEuropeanCricketer = objEuropeanFactory.GetCricketer(CricketerBase.EnglishCricketer);
            Console.WriteLine("England Cricket Team\nBatting Strength:" + objIEuropeanCricketer.BattingStrength());

            Console.WriteLine("Bowling Strength:" + objIEuropeanCricketer.BowlingStrength());
            Console.WriteLine("Allrounding Strength:" + objIEuropeanCricketer.AllroundingStrength());
            Console.WriteLine("Icon Player:" + objIEuropeanCricketer.IconPlayer());


            Console.ReadLine();


        }
    }
}


Step 11: Output


31 July, 2012

Factory Design Pattern


Factory design pattern implements the concept of real world factories. Factory pattern is a creational design pattern. It deals with creating object without specifying exact class. In general, actors of factory patterns are a client, a factory and a product. Client is an object that requires another object for some purposes. Rather than creating the product instance directly, the client delegates this responsibility to the factory. The factory then creates a new instance of the product, passing it back to the client. Figure shows the whole process.

 
Application
For an example, a banking application works with accounts. In this application there are different types of account like saving account and checking account. All accounts are derived from an abstract account name IAccount. The IAccount defines the withdraw, deposit and interest rate which must be implemented by the concrete accounts (saving account, checking account). If clients want to know the interest rate of the Saving Account. It just invoke the factory to create an instance of Saving account.  Being invoked factory, it creates an instance of the saving account and then client just get the interest rate by invoking interest method. The client uses the object as casted to the abstract class without being aware of the concrete object type. Over all implementation of this scenario is given below.

The advantage is in here that new account can be added without changing a single line of code in the client code. Here an object is created without exposing instantiation logic to the client. The object generation is centralized here.

Benefits:
  • Factory Pattern is the mostly used pattern.
  •  Decoupled the classes i.e eliminates the need to bind application specific class
  • The code only deals with the Interface.
  •  Factory Pattern provides the way to create multiple instances of classes.
  •  This provides a hook so that we can derive a sub-class to create different controls to display the data.
  •   Factory method connects the class hierarchies with minimum coupling.
  •  Product implementation may change over time but client remains unchanged.

Implementation
Step 1: Create an Interface - IAccount
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FactoryPattern
{
    public interface IAccount
    {
        string Withdraw(int amount);
        string Deposit(int amount);

        double InterestRate();
    }
} 

Step 2: Create concrete classes

Saving account
 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FactoryPattern
{
    /// 
    /// Concrete class SavingsAccount
    /// 
    public class SavingsAccount : IAccount
    {
        #region IAccount Members

        public string Withdraw(int amount)
        {
            throw new NotImplementedException();
        }

        public string Deposit(int amount)
        {
            throw new NotImplementedException();
        }

        public double InterestRate()
        {
            return 12.5;
        }

        #endregion
    }
}


Checking Account


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FactoryPattern
{

    /// 
    /// Concrete class CheckingAccount
    /// 
    public class CheckingAccount : IAccount
    {
        #region IAccount Members

        public string Withdraw(int amount)
        {
            throw new NotImplementedException();
        }

        public string Deposit(int amount)
        {
            throw new NotImplementedException();
        }

        public double InterestRate()
        {
            return 10.24;
        }

        #endregion
    }
} 


Step 3: Create a Factory Object Enum
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FactoryPattern
{
    /// 
    /// FactoryObject Enum to configure object
    /// 
    public enum FactoryObject
    {
        SavingAccount,
        CheckingAccount
    }
}

Step 4: Create a factory class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FactoryPattern
{
    /// 
    /// Factory class to create object
    /// 
    public static class Factory
    {
        public static IAccount CreateObject(FactoryObject factoryObject)
        {
            IAccount objIAccount = null;

            switch (factoryObject)
            {
                case FactoryObject.SavingAccount:
                    objIAccount = new SavingsAccount();
                    break;

                case FactoryObject.CheckingAccount:
                    objIAccount = new CheckingAccount();
                    break;

                default:
                    break;
            }

            return objIAccount;
        }
    }
}


Step 5: Access from client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FactoryPattern
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //Create object by factory pattern
            IAccount objSavingAccount = Factory.CreateObject(FactoryObject.SavingAccount);
            IAccount objCheckingAccount = Factory.CreateObject(FactoryObject.CheckingAccount);

            //Access object
            Console.WriteLine("Saving Account Interest Rate: " + objSavingAccount.InterestRate());
            Console.WriteLine("Checking Account Interest Rate: " + objCheckingAccount.InterestRate());


            Console.ReadLine();
            
        }
    }
}

28 July, 2012

Singleton Design Pattern

Design Pattern
 Design pattern is a solution of known problems. These are strategies of solving commonly occurring problems. A design pattern is not a finish design. It is like a template to solve a problem.  

Singleton Design Pattern
Singleton is a software design pattern. It is restrict to create object more than once. This is actually needed when one object can perform its action in whole system. We frequently use a database connection object to connect with database. We don’t need multiple objects to create connection with database and close it. We can use singleton in this scenario.


Implementation of Singleton by C#

Step 1: Create EmployeeInfo class
This class is to hold employee information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Singleton
{
    public class EmployeeInfo
    {
        public string EmpName { get; set; }
        public string EmpDesignation { get; set; }
        public int MonthlySalary { get; set; }
    }
}


Step 2: Create a singleton class
 Here EmployeeService is a singleton class. Constructor of this class is private so that nobody can create its instance from outside.  Instance() is a static method which creates instance of the singleton class. It actually forces that only one instance of the object will be created. Lock() is used to create instance of the singleton pattern in thread safe manner in multi threaded environment. The other two methods are used to add employee information in list and get employee salary. These two are as usual method. Don’t mix up Singleton class and Static class. Keep in mind; in static class everything must be static like Method, constructor, properties. But in singleton class it is not required. Hope, you will be clear after the following example.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Singleton
{
    /// 
    /// EmployeeService is a singleton class
    /// 
    public class EmployeeService
    {

        //Static object of singleton class
        private static EmployeeService instance;

        private List lstEmployeeInfo = null;

        /// 
        /// Restrict to create object of Singleton class
        /// 
        private EmployeeService()
        {
            if (lstEmployeeInfo == null)
            {
                lstEmployeeInfo = new List();
            }
        }


        /// 
        /// The static method to provide global access to the singleton object.
        /// 
        /// Singleton object of EmployeeService class
        public static EmployeeService Instance()
        {
            
            if (instance == null)
            {
                //Thread safe singleton

                lock (typeof(EmployeeService))
                {
                    instance = new EmployeeService();
                }
            }

            return instance;
        }


        /// 
        /// Add employee information to the Employee information list
        /// 
        /// 

        public void AddEmployeeInfo(EmployeeInfo objEmployeeInfo)
        {
            lstEmployeeInfo.Add(objEmployeeInfo);
        }


        /// 
        /// Get Salary by Name
        /// 
        /// 
        /// Salary of Employee
        
        public int GetEmployeeSalaryByName(string name)
        {
            int monthlySalary = 0;
            foreach (EmployeeInfo objEmployeeInfo in lstEmployeeInfo)
            {
                if (objEmployeeInfo.EmpName.Contains(name))
                    monthlySalary = objEmployeeInfo.MonthlySalary;
            }
            return monthlySalary;
        }

    }
}




Step 3: Access singleton class
This class creates an instance of singleton class by EmployeeService objEmployeeService = EmployeeService.Instance(); and access singleton class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Singleton
{
    class Program
    {
        static void Main(string[] args)
        {
            EmployeeInfo objEmpInfo1 = new EmployeeInfo() { EmpName = "Mahedee", EmpDesignation = "Senior Software Engineer", MonthlySalary = 00000 };
            EmployeeInfo objEmpInfo2 = new EmployeeInfo() { EmpName = "Kamal", EmpDesignation = "Software Engineer", MonthlySalary = 30000 };


            //Create a singleton object
            EmployeeService objEmployeeService = EmployeeService.Instance();
            

            objEmployeeService.AddEmployeeInfo(objEmpInfo1);
            objEmployeeService.AddEmployeeInfo(objEmpInfo2);

            Console.WriteLine(objEmpInfo2.EmpName + " : " + objEmployeeService.GetEmployeeSalaryByName("Kamal"));

            Console.ReadLine();

        }
    }
}