Tuesday, February 18, 2014

Overview of Design Pattern

Hello again ,
This is last article about design pattern .
In this article we will check what are different design pattern and how and when they are implemented.



Design Patterns provide standardized and efficient solutions to software design and programming problems that are re-usable in your code. Software Architects and developers use them to build high quality robust applications.

The GoF Design Patterns are divided into 3 categories : Creational Patterns, Structural Patterns and Behavioral Patterns. I am going to explain each GoF Design Pattern in detail and will show you examples of how to write good C# 4.0 code that implement those patterns.
Creational Patterns
Structural Patterns
  • Adapter Pattern: Match interfaces of classes with different interfaces
  • Bridge Pattern:: Separate implementation and object interfaces
  • Composite: Simple and composite objects tree
  • Decorator: Dynamically add responsibilities to objects
  • Facade: Class that represents subclasses and subsystems
  • Flyweight: Minimize memory usage by sharing as much data as possible with similar objects
  • Proxy: Object that represents another object
Behavioral Patterns
  • Chain of Responsibility: Pass requests between command and processing objects within a chain of objects
  • Command: Encapsulate a method call as an object containing all necessary information
  • Interpreter: Include language elements and evaluate sentences in a given language
  • Iterator: Give sequential access to elements in a collection
  • Mediator: Encapsulates and simplifies communication between objects
  • Memento: Undo modifications and restore an object to its initial state
  • Observer: Notify dependent objects of state changes
  • State: Change object behavior depending on its state
  • Strategy: Encapsulate algorithms within a class and make them interchangeable
  • Template Method: Define an algorithm skeleton and delegate algorithm steps to subclasses so that they may be overridden
  • Visitor: Add new operations to classes without modifying them


Hope it help you for quick reference.

Regards
Amey 
Start where you are. Use what you have.  Do what you can.



Common Design Patterns in C# 4.0- Singleton Pattern


Hello again ,
Last time we discussed about different Factory Patter .
This time we will learn about the Singleton Pattern.
THis article is at CodePlex 
Pattern Name:
Singleton Pattern
Short Description:
Class with only one single possible instance
Usage:
Often used for objects that need to provide global access with the constraint of only one single instance in the application
Complexity:
1 / 5
UML Class Diagram:
image_thumb2_thumb[2]
Explanation:
  • There are multiple ways of implementing the Singleton Pattern in C#. I am going to explain the most efficient approaches that also provide thread safety.
  • Note that in the first example the default constructor is defined as private so that it is not possible to instantiate the object from the outside. The class is also marked as sealed which means that inheritance is not allowed for it.
  • The internally instantiated object is stored in a private variable that is marked as static. The public static property GetInstance is used to allow access to this object. It contains the business logic that assures that only a single instance can ever exist.
  • To achieve this behavior a lock strategy is used to assure that only a single thread is allowed to do the null check and create a new instance if it does not already exist.
  • A test function DisplayConfiguration() was added to be able to verify the class design.
    public sealed class ConfigurationManager
    {
        private static ConfigurationManager instance;
        private static object syncRoot = new Object();

        private ConfigurationManager()
        {
       
        }

        public static ConfigurationManager GetInstance
        {
            get
            {
                lock (syncRoot)
                {
                    if (instance == null)
                    {
                        instance = new ConfigurationManager();
                    }
                }

                return instance;
            }
        }

        public void DisplayConfiguration()
        {
            Console.WriteLine("Single instance object");
        }
    }
  • Note that in the second example the default constructor is also defined as private so that it is not possible to instantiate the object from the outside. The class is also marked as sealed which means that inheritance is not allowed for it.
  • This time a private nested class is used to provide access to the instance that must only exist once in the application.
  • This nested class has a static default constructor and an internal static read-only instance of the object. Only the container class has access to the instance which will due to the software design (auto-instantiated and marked as read-only) only exist once.
  • A test function DisplayRules() was added to be able to verify the class design.
  • I recommend using this example as your default approach for your Singleton implementations since there is no locking in it which makes it more efficient in terms of performance.
    public sealed class BusinessRulesManager
    {
        private BusinessRulesManager()
        {

        }

        public static BusinessRulesManager GetInstance
        {
            get
            {
                return BusinessRulesManagerImpl.instance;
            }
        }

        public void DisplayRules()
        {
            Console.WriteLine("Single instance object");
        }

        private class BusinessRulesManagerImpl
        {
            static BusinessRulesManagerImpl()
            {

            }

            internal static readonly BusinessRulesManager instance = new BusinessRulesManager();
        }
    }
  • In the last step we add some code to test the software design and the Singleton implementation.
    private static void Singleton()
    {
        var configurationManager = ConfigurationManager.GetInstance;
        configurationManager.DisplayConfiguration();

        var businessRulesManager = BusinessRulesManager.GetInstance;
        businessRulesManager.DisplayRules();

        Console.ReadKey();
    }
  • When running the example you can see that everything is working as expected (it is however not as simple to test that there really is just one single instance, you just have to believe in the correct software design).
image_thumb_thumb[1]





Regards
Amey 
Start where you are. Use what you have.  Do what you can.

Common Design Patterns in C# 4.0- Factory Method


Hello again ,
Last time we discussed about Abstract Factory Pattern.
Today we will learn about the Factory Pattern.

I got this article at CodePlex 

Pattern Name:
Factory Method
Short Description: 
Create instances of derived classes
Usage:
Frequently used, fairly easy to implement and useful for centralizing object lifetime management and avoiding object creation code duplication
Complexity:
1 / 5
UML Class Diagram:
image
Explanation:
  • The abstract creator implements a factory method that returns an objects. It also contains a method for testing purposes that serves to validate the design.
  • Each concrete creator overrides the abstract factory method and returns a specific object concerning on the context.
  • In this example the factory method is used internally to set a property but it could also be used in an external context for creating objects when needed.
    public abstract class BookReader
    {
        public BookReader()
        {
            Book = BuyBook();
        }

        public Book Book { get; set; }

        public abstract Book BuyBook();

       
        public void DisplayOwnedBooks()
        {
            Console.WriteLine(Book.GetType().ToString());
        }
    }

    public class HorrorBookReader : BookReader
    {
        public override Book BuyBook()
        {
            return new Dracula();
        }
    }

    public class FantasyBookReader : BookReader
    {
        public override Book BuyBook()
        {
            return new LordOfTheRings();
        }
    }

    public class AdventureBookReader : BookReader
    {
        public override Book BuyBook()
        {
            return new TreasureIsland();
        }
    }
  • The abstract class defines the interface and class structure for all objects that get build by the specific concrete creators via their factory methods.
    public abstract class Book
    {
    }

    public class Dracula : Book
    {
    }

    public class LordOfTheRings : Book
    {
    }

    public class TreasureIsland : Book
    {
    }

    public class Encyclopedia : Book
    {
    }
  • There is also the possibility to create a C# specific solution that uses generics which also results in a valid factory method.
    public Book BuyBook<T>()
        where T : Book, new()
    {
        return new T();
    }
  • In the last step we add some code to test the software design and the Factory Method implementation in the language agnostic and in the C# specific versions.
    private static void FactoryMethod()
    {
        var bookReaderList = new List<BookReader>();

        bookReaderList.Add(new AdventureBookReader());
        bookReaderList.Add(new FantasyBookReader());
        bookReaderList.Add(new HorrorBookReader());

        foreach (var reader in bookReaderList)
        {
            Console.WriteLine(reader.GetType() .ToString());
            // language agnostic solution
            reader.DisplayOwnedBooks();

            Console.WriteLine();
        }

        // C# specific solution using generics
        var genericReader = new AdventureBookReader();
        Book book = genericReader.BuyBook<Encyclopedia>();
        Console.WriteLine(book.GetType().ToString());

        Console.ReadKey();
    }
  • When running the example you can see that everything is working as expected and that the correct classes are instantiated during runtime.
image


Common Design Patterns in C# 4.0- Abstract Factory Pattern


Hello again ,
Last time we discussed about different Design pattern used .
Today we will learn about the Abstract Factory Pattern.

I get very good article at CodePlex 


Pattern Name:
Abstract Factory Pattern
Short Description:
Create instances of classes belonging to different families
Usage:
Very frequently used and very useful
Complexity:
1 / 5
UML Class Diagram:
image
Explanation:
  • The abstract factory class defines the abstract methods that have to be implemented by concrete factory classes. It serves as interface and contract definition.
  • The concrete factory classes contain the real implementation that define which classes are created during run-time.
  • Note that the methods return values are also defined by abstract classes, this allows a high flexibility and independence, leading to methods that must only be implemented once.
  • The returned classes are however specific to each concrete factory class (you will see their implementation below).
    public abstract class CarFactory
    {
        public abstract SportsCar CreateSportsCar();
        public abstract FamilyCar CreateFamilyCar();
    }

    public class AudiFactory : CarFactory
    {
        public override SportsCar CreateSportsCar()
        {
            return new AudiSportsCar();
        }

        public override FamilyCar CreateFamilyCar()
        {
            return new AudiFamilyCar();
        }
    }

    public class MercedesFactory : CarFactory
    {
        public override SportsCar CreateSportsCar()
        {
            return new MercedesSportsCar();
        }

        public override FamilyCar CreateFamilyCar()
        {
            return new MercedesFamilyCar();
        }
    }
  • Here you see the abstract classes that are used during the creation process (a method was added that serves to prove the validity of the design).
  • Based on the abstract classes some real example implementation are created, those will be instantiated during run-time, depending on the concrete factory that creates them.
    public abstract class SportsCar
    {
    }

    public abstract class FamilyCar
    {
        public abstract void Speed(SportsCar abstractFamilyCar);
    }

    class MercedesSportsCar : SportsCar
    {
    }
   
    class MercedesFamilyCar : FamilyCar
    {
        public override void Speed(SportsCar abstractSportsCar)
        {
            Console.WriteLine(GetType().Name + " is slower than "
                + abstractSportsCar.GetType().Name);
        }
    }

    class AudiSportsCar : SportsCar
    {
    }

    class AudiFamilyCar : FamilyCar
    {
        public override void Speed(SportsCar abstractSportsCar)
        {
            Console.WriteLine(GetType().Name + " is slower than "
                + abstractSportsCar.GetType().Name);
        }
    }
  • When implementing the associations between the Driver class, the abstract factory class and the abstract classes you may either use the common language agnostic approach using only private members (which is the most memory efficient one).
    public class Driver
    {
        private SportsCar _sportsCar;
        private FamilyCar _familyCar;

        public Driver(CarFactory carFactory)
        {
            _sportsCar = carFactory.CreateSportsCar();
            _familyCar = carFactory.CreateFamilyCar();
        }

        public void CompareSpeed()
        {
            _familyCar.Speed(_sportsCar);
        }
    }
  • Or you may use the C# language specific approach where everything is wrapped using private properties. This allows adding logic when accessing or changing the private members but might be a little overkill (this is also what gets auto-generated when modeling using the class diagram).
    public class Driver
    {
        private CarFactory _carFactory;
        private SportsCar _sportsCar;
        private FamilyCar _familyCar;

        public Driver(CarFactory carFactory)
        {
            CarFactory = carFactory;
            SportsCar = CarFactory.CreateSportsCar();
            FamilyCar = CarFactory.CreateFamilyCar();
        }

        private CarFactory CarFactory
        {
            get { return _carFactory; }
            set { _carFactory = value; }
        }

        private SportsCar SportsCar
        {
            get { return _sportsCar; }
            set { _sportsCar = value; }
        }

        private FamilyCar FamilyCar
        {
            get { return _familyCar; }
            set { _familyCar = value; }
        }

        public void CompareSpeed()
        {
            FamilyCar.Speed(SportsCar);
        }
    }
  • You may also use another C# language specific solution that uses generic classes to create objects and that is also a valid implementation for the abstract factory pattern.
    public class GenericFactory<T>
        where T : new()
    {
        public T CreateObject()
        {
            return new T();
        }
    }
  • In the last step we add some code to test the software design and the Abstract Factory implementation.
    public static void AbstractFactory()
    {
        // Language agnostic version
        CarFactory audiFactory = new AudiFactory();
        Driver driver1 = new Driver(audiFactory);
        driver1.CompareSpeed(); ;

        CarFactory mercedesFactory = new MercedesFactory();
        Driver driver2 = new Driver(mercedesFactory);
        driver2.CompareSpeed();

        // C# specific version using generics
        var factory = new GenericFactory<MercedesSportsCar>();
        var mercedesSportsCar = factory.CreateObject();
        Console.WriteLine(mercedesSportsCar.GetType().ToString());

        Console.ReadKey();
    }
  • When running the example you can see that everything is working as expected and that the correct classes are instantiated during runtime.




 try it Its one of simplest explanation i found on google


Regards
Amey 
Start where you are. Use what you have.  Do what you can.

Design Pattern

Recently I was searching for different design pattern and I came to a very good and easy to learn document.
So I thought to share it with you …
I found it at below link


What is a Design Pattern?
Design Pattern is a re-usable, high quality solution to a given requirement, task or recurring problem. Further, it does not
comprise of a complete solution that may be instantly converted to a code component, rather it provides a framework for how
to solve a problem.
In 1994, the release of the book Design Patterns, Elements of Reusable Object Oriented Software made design patterns
popular.
Because design patterns consist of proven reusable architectural concepts, they are reliable and they speed up software
development process.
Design Patterns are in a continious phase of evolution, which means that they keep on getting better & better as they are
tested against time, reliability and subjected to continious improvements. Further, design patterns have evolved towards
targeting specific domains. For example, windows-based banking applications are usually based on singleton patterns,
e-commerce web applications are based on the MVC (Model-View-Controller) pattern.

Design Patterns are categorized into 3 types:
Creational Patterns
Structural Patterns
Behavioral Patterns
What are Creational Design Patterns?
The Creational Design Patterns focus on how objects are created and utilized in an application. They tackle the aspects of
when and how objects are created, keeping in mind whats the best way these objects should be created.
Listed below are some of the commonly known Creational Design Patterns:
>>> Abstract Factory Pattern
>>> Factory Pattern
>>> Builder Pattern
>>> Lazy Pattern
>>> Prototype Pattern
>>> Singleton Pattern
Whats the difference between Abstract Factory Pattern and Factory Pattern?
In an abstract factory design, a framework is provided for creating sub-components that inherit from a common component.
In .NET, this is achieved by creating classes that implement a common interface or a set of interfaces, where the interface
comprises of the generic method declarations that are passed on to the sub-components. TNote that not just interfaces, but
even abstract classes can provide the platform of creating an application based on the abstract factory pattern.
Example, say a class called CentralGovernmentRules is the abstract factory class, comprised of methods like
ShouldHavePolice() and ShouldHaveCourts(). There may be several sub-classes like State1Rules, State2Rules etc. created
that inheriting the class CentralGovernmentRules, and thus deriving its methods as well.
Note that the term "Factory" refers to the location in the code where the code is created.
A Factory Pattern is again an Object creation pattern. Here objects are created without knowing the class of the object.
Sounds strange? Well, actually this means that the object is created by a method of the class, and not by the class's
constructor. So basically the Factory Pattern is used wherever sub classes are given the priviledge of instantiating a method
that can create an object.
Describe the Builder Design Pattern
In a builder design pattern, an object creation process is separated from the object design construct. This is useful becuase
the same method that deals with construction of the object, can be used to construct different design constructs.
What is the Lazy Design Pattern?
The approach of the Lazy Design Pattern is not to create objects until a specific requirement matches, and when it matches,
object creation is triggered. A simple example of this pattern is a Job Portal application. Say you register yourself in that site
thus filling up the registration table, only when the registration table is filled, the other objects are created and invoked, that
prompt you to fill in other details too, which will be saved in other tables.

What is the Prototype Design Pattern?
A prototype design pattern relies on creation of clones rather than objects. Here, we avoid using the keyword 'new' to prevent
overheads.
What is the Singleton Design Pattern?
The Singleton design pattern is based on the concept of restricting the instantiation of a class to one object. Say one object
needs to perform the role of a coordinator between various instances of the application that depend on a common object, we
may design an application using a Singleton. Usage of Singleton patterns is common in Banking, Financial and Travel based
applications where the singleton object consists of the network related information.
A singleton class may be used to instantiate an object of it, only if that object does not already exist. In case the object exists,
a reference to the existing object is given. A singleton object has one global point of access to it.
An ASP.NET Web Farm is also based on the Singleton pattern. In a Web Farm, the web application resides on several web
servers. The session state is handled by a Singleton object in the form of the aspnet_state.exe, that interacts with the
ASP.NET worker process running on each web server. Note that the worker process is the aspnet_wp.exe process. Imagine
one of the web servers shutting down, the singleton object aspnet_state.exe still maintains the session state information
across all web servers in the web farm.
In .NET, in order to create a singleton, a class is created with a private constructor, and a "static readonly" variable as the
member that behaves as the instance.
What are Structural Design Patterns?
A structural design pattern establishes a relationship between entities. Thus making it easier for different components of an
application to interact with each other. Following are some of the commonly known structural patterns:
>>> Adapter Pattern - Interfaces of classes vary depending on the requirement.
>>> Bridge Pattern - Class level abstraction is separated from its implementation.
>>> Composite Pattern - Individual objects & a group of objects are treated similarly in this approach.
>>> Decorator Pattern - Functionality is assigned to an object.
>>> Facade Pattern - A common interface is created for a group of interfaces sharing a similarity.
>>> Flyweight Pattern - The concept of sharing a group of small sized objects.
>>> Proxy Pattern - When an object is complex and needs to be shared, its copies are made. These copies are called
the proxy objects.
What are the different types of Proxy Patterns?
1 - Remote Proxy - A reference is given to a different object in a different memory location. This may be on a different or a
same machine.
2 - Virtual Proxy - This kind of object is created only & only when really required because of its memory usage.
3 - Cache Proxy - An object that behaves as a temporary storage so that multiple applications may use it. For example, in
ASP.NET when a page or a user control contains the OutputCache directive, that page/control is cached for some time on the
ASP.NET web server.
What is a behavioral design pattern?
Behaviorial design patterns focus on improving the communication between different objects. Following are different types of
behavioral patterns:
>>> Chain Or Responsibilities Pattern - In this pattern, objects communicate with each other depending on logical decisions
made by a class.
>>> Command Pattern - In this pattern, objects encapsulate methods and the parameters passed to them.
>>> Observer Pattern - Objects are created depending on an events results, for which there are event handlers created.
What is the MVC Pattern (Model View Controller Pattern)?
The MVC Pattern (Model View Controller Pattern) is based on the concept of designing an application by dividing its
functionalities into 3 layers. Its like a triad of components. The Model component contains the business logic, or the other set


How many design patterns can be created in .NET?
As many as one can think. Design patterns are not technology specific, rather their foundation relies on the concept of
reusability, object creation and communication. Design patterns can be created in any language.
Describe the Ajax Design Pattern.
In an Ajax Design Pattern, partial postbacks are triggered asyncronously to a web server for getting live data. A web
application would not flicker here, and the web site user would not even come to know that a request is being sent to the web
server for live data.
Such a design pattern is used in applications like Stock Market Websites to get live quotes, News Websites for live news,

Sports websites for live scores etc.




It help me to understand the different design pattern and its working . Hope it help you too.
If you like this please share it .

Regards
Amey
Start where you are. Use what you have.  Do what you can.