Saturday 21 May 2011

Design Patterns


I am starting to write articles on design patterns. We have 3 types of design patterns as per GoF. There are plenty of design patterns available but 23 standard pattern I am going to cover in my article. Design patterns are Solutions to commonly occurring design problem. Someone has already faced the problem and come up with good and elegant solution. The same pattern you have to use. Design Pattern divided into 3 categories.
  1. Creational
  2. Behavioral
  3. Structural
    1. Creational
      Concerned about ways to create new objects.  
    2. Behavioral
      Concerned about ways in which objects interacted  
    3. Strucural
      Concerned about the composition of objects and classes
Creational Patterns
SingletonTo Create a sole instance of a class
PrototypeTo create object by cloning existing object.
BuilderBuild an object from existing representation
Factory MethodDefer instantiation to subclass
Abstract FactoryProvides interface to create families of objects without specifying the concrete classes of the objects
Structural Patterns
AdapterConvert an instance to another
CompositeComposite objects in a tree structure
DecoratorAttach additional responsibilities dynamically
ProxyProvide a surrogate or placeholder for another object
FaçadeProvide a unified instance to a set of instances in sub system
BridgeDecouple abstraction from implementation. Let them vary and independent.
FlyweightA fine-grained instance user for efficient sharing
Behavioral Pattern
Chain of Resp.Delegates commands to a chain of processing objects.
CommandCreates objects which encapsulate actions and parameters.
InterpreterImplements a specialized language.
IteratorAccesses the elements of an object sequentially without exposing its underlying representation.
MediatorAllows loose coupling between classes by being the only class that has detailed knowledge of their methods.
MementoProvides the ability to restore an object to its previous state (undo).
ObserverPublish/subscribe pattern which allows a number of observer objects to see an event.
StateAllows an object to alter its behavior when it's internal state changes.
StrategyAllows one of a family of algorithms to be selected on-the-fly at runtime.
Template MethodDefines the skeleton of an algorithm as an abstract class, allowing its subclasses to provide concrete behavior.
VisitorSeparates an algorithm from an object structure by moving the hierarchy of methods into one object.

Reference Books

C# 3.0 Design Patterns
Design Patterns in C#

C# 3.0 Design Patterns
Agile Principles, Patterns, and Practices in C#
Pro .NET 4 Parallel Programming in C# (Expert's Voice in .NET)
C# Design Patterns: A Tutorial

Friday 13 May 2011

Delegates and Events

Delegates

Delegate is pointer to function. In other way we can say that delegate holds the reference of the function. Instead of calling the function we calling the delegate. Signature of the delegate and signature function should be same. In below example we declare delegate which is not taking any parameter and not returning any value. After understanding delegate I am listing benefits of delegate.

Code Example

namespace BasicDelegate
{

    // Declaration
    public delegate void MyDelegate();


    class DelegateExample
    {
        public static void MyFunction()
        {
            Console.WriteLine("I was called by delegate ...");
        }


        static void Main(string[] args)
        {
            MyDelegate myDelegate = new MyDelegate(MyFunction);
            myDelegate();
            Console.ReadLine();

        }
    }
}


Events

The basic of the event is publisher and subscriber.  Publishers object publish event and any number of object can be subscribe to publisher object. To declare event first we have to declare a delegate. By using delegate event should be declared. In below example we have publisher class which is publishing the event and subscriber class is Program.

Code Example

Main Method
class Program
    {
        //This is simple method which will write into console
        static void Logger(string s)
        {
            Console.WriteLine(s);
        }

        static void Main(string[] args)
        {
            FileLoggerClass fl = new FileLoggerClass("process.log");
            PublisherClass publisherClass = new PublisherClass();

            // Subscribe the Functions Logger and fl.Logger
            publisherClass.Log += new PublisherClass.LogHandler(Logger);
            publisherClass.Log += new PublisherClass.LogHandler(fl.LoggerMethod);

            // The Event will now be triggered in the Process() Method
            publisherClass.Process();

            fl.Close();

        }
    }


Publisher Class
class PublisherClass
    {
        public delegate void LogHandler(string message);
        // Define an Event based on the above Delegate
        public event LogHandler Log;
        // Instead of having the Process() function take a delegate
        // as a parameter, we've declared a Log event. Call the Event,
        // using the OnXXXX Method, where XXXX is the name of the Event.
        public void Process()
        {
            OnLog("Process() begin");
            OnLog("Process() end");
        }
        // By Default, create an OnXXXX Method, to call the Event
        protected void OnLog(string message)
        {
            if (Log != null)
            {
                Log(message);
            }
        }
    }

Simple File logger class

class FileLoggerClass
    {
        FileStream fileStream;
        StreamWriter streamWriter;

        // Constructor
        public FileLoggerClass(string filename)
        {
            fileStream = new FileStream(filename, FileMode.Create);
            streamWriter = new StreamWriter(fileStream);
        }

        // Member Function which is used in the Delegate
        public void LoggerMethod(string s)
        {
            streamWriter.WriteLine(s);
        }

        public void Close()
        {
            streamWriter.Close();
            fileStream.Close();
        }

    }

Saturday 7 May 2011

Design Principles

1. Open Close Principle
Software entities like classes, modules and functions should be open for extension but closed for modifications.

2. Dependency Inversion
High-level modules should not depend on low-level modules. Both should depend on abstractions.
Abstractions should not depend on details. Details should depend on abstractions
3. Interface Segregation
Clients should not be forced to depend upon interfaces that they don't use.

4. Single Responsibility
A class should have only one reason to change.

Composition and Aggregation

Composition

1. Compostion is 'Part of' Relation.
2. The life time of the object managed by main class. If main class
destroyed composited object also destroyed.
3. In UML diagram composition shows with filled diagram.

in below example if Car object destroyed Engine object also destroyed.



Aggregation

Agregation gives 'has a' relationship. Even if main objecte destroyed aggregated object does not destroyed.
If you take Customer class and Address Class. We can say that customer has address we dont say Address is part of the customer. Aggregation show in UML diagram with unfilled diamond.

Monday 2 May 2011

Reflection in .NET

Reflection - The process of getting the metadata from modules/assemblies. When .NET code is compiled, metadata about the types defined in the modules is produced. These modules are in turn packaged as assemblied. The process of accessing this metadata in called Reflection.
The namespace System.Reflection contains classes that can be used for interrogating the types for a module/assembly. We use reflection for examining data type sizes for marshalling across process & machine boundaries.

.NET Framework's Reflection API allows you to fetch type (assembly) information at runtime programmatically. We can also achieve late binding by using .NET Reflection. At runtime, the Reflection mechanism uses the PE file to read information about the assembly. Reflection enables you to use code that is not available at compile time. .NET Reflection allows an application to collect information about itself and also to manipulate on itself. It can be used effectively to find all types in an assembly and/or dynamically invoke methods in an assembly. This includes information about the type, properties, methods, and events of an object. With Reflection, we can dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. We can also access attribute information using Reflection.

Assembly contain the modules, modules contain the types and type contain members. You can use the reflection to create the instance of the types dynamically. You can invoke the type's method dynamically and can access the fields information.

List of classes which we using in reflection:
  1. Assemly
  2. Module
  3. ConstructorInfo
  4. MethodInfo
  5. FieldInfo
  6. EventInfo
  7. PropertyInfo
  8. ParameterInfo