Feb 05

A Question from a reader and my Answer

C# | Design Patterns | My Inbox 4 Comments »

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Greetings!

I have a hierarchy of classes, with an abstract class that defines the
method Read() at the top of it. Each class in the hierarchy has a
Read() method, and I need to be able to call Read() from the highest
possible level of the hierarchy and get the correct Read() function.

Public class AbstractClass 
{
abstract void Read();
}

Public class A : AbstractClass
{
public override void Read();
}

Public class B: A
{
public override void Read();
}

The compiler complains that A has no overridable function named Read().
Is it not possible to do this?

Thank you very much.

RobR


[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

Oct 22

Singleton design pattern

C# | Design Patterns 75 Comments »

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
IMPORTANT:  The example code which i discussed is attached at the end of this post. You can download it to compile.
 
 
  Singleton assures that there is one and only one instance of a class and provides a global point of access to it.
Why Singleton:
There are number of cases in programming when we want a class to have only one instance. e.g.
  •  Sometimes we want just a single instance of a class to exist in the system.
  • We need to have that one instance easily accessible
  • And we want to ensure that additional instances of the class can not be
    created
How to Implement Singleton pattern in C Sharp:
Ok, now we have understand that why we need the singleton, now the question is that how to implement this?
We will do two things to implement the singleton pattern which are given below:
  1. Declare a static Boolean variable to keep track that instance of the class is created or not.
  2. The constructor of the class should be private.
Now lets dig into the above two points that how these two points will be used to implement the singleton:

First we stated that we will declare a static boolean variable to keep track that the instance of the class is created or not. Secondly we stated that we will make that constructor of that class private.

This was all theory, now lets try to make our hands dirty with the code.

First of all I need to declare my class which should have the one and only one instance. Lets say I gave it the name "MySingleton". Now I will write code to accommodate my two points which I mentioned previously.
///
/// The following class will behave as singleton
///
class MySingleton
{
// The following is a static variable which
// will be used to keep the track that instance
// of this class is created or not.
private static bool IsAlreadyCreated = false;
///
/// Constructor of the class. It is declared private
/// so no one would be able to create the instance of
/// this class.
///
private MySingleton()
{
// I declared it private so now no one
// would be able to create the instance
// this class

}
///
/// It is static method. I declared it static, because
/// I have designed the class in such a way that the
/// instance of this class can not be created. And We know
/// that static method can be accessed without declaring
/// the instance of the class.
/// This method will check the static boolean variable which
/// we declared in the class. If the boolean variable is false
/// then It will return the instance of the MySingleton class.
/// Else if will return null
///
///
public static MySingleton GetSingletonHandle()
{
if (!IsAlreadyCreated)
{
IsAlreadyCreated = true;
return new MySingleton();
}
else
{
throw new MyException("Get last, I can not give you more than one handle");
}
}
}

The above code is commented and self explanatory. Now lets start write code to check our class.

In the Main program write the following line:
MySingleton _MySingleton = MySingleton.GetSingletonHandle();
if (_MySingleton != null)
{
Console.WriteLine("Instance is created");
}
else
{
Console.WriteLine("I cant not give more than one handle");
}

In the above code I am trying to get the "GetSingletonHandle()" from the MySingleton class. Here this point must be noted that the following line
MySingleton _MySingleton is just the object of the MySingleton class. It is not instantiating the instance of the class. The instance is created by using the new keyword, like this:
MySingleton _MySingleton = new MySingleton();

Ok, after getting the "GetSingletonHandle()" from the MySingleton class, I am checking that what I got (i.e. Is it null or not).
What is the meaning if I am getting null??
It means that the instance of this class was already created, and if its not null then it means that we have got the GetSingletonHandle.

Out put:
If you run program you will get the out put some thing like this:

You got the Handle

Upto this point we are almost finished with the Singleton design pattern. But I am not satisfied with the Main program which is trying to get the GetSingletonHandle(), Why?
  • Do you think that it is a good approach to always check that GetLogErrorhandle() is null or not?
If yes, then you are wrong and if no then also you are wrong. :)
If your answer is yes, then I must say that bad developers like me forgot to check these kinds of basic thing that the object on which I am going to perform some operation is null or not. So to make the life easy for the developers like me It would be good to design the singleton to throw a custom exception instead of sending null if its object is already created.

If your answer was no, then again you are wrong becasue there is no fault in the singleton class, It was my mistake that I always forgot to check the basic null checks. :)

So why not to write a small class of my own custom exception. And in the singleton class I will make use of that custom exception (i.e. if the instance was already created then throw the exception rather than throwing the null).

Ok, so here is the code of my Custome Exception class:


public class MyException: Exception
{
public SingletonException(string s) : base(s)
{
}
}

Now lets change in the GetSingletonHandle function of our Singleton class to make use of the above exception class.

public static MySingleton GetSingletonHandle()
        {
            if (!IsAlreadyCreated)
            {
                IsAlreadyCreated = true;
                return new MySingleton();
            }
            else
            {
                throw new MyException("Get last, I can not give you more than one handle");
            }
        }

}
}

Now run the program, you will get the same output. To check our complete program which we have written, we need to change our Main program, so that we can check that what happened If I asked my singleton to give me more than one handle.

My Complete program is now given below:

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

namespace Singleton
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                MySingleton _MySingleton = MySingleton.GetSingletonHandle();
                if (_MySingleton != null)
                {
                    Console.WriteLine("Instance is created");
                }
                MySingleton _MySingleton2 = MySingleton.GetSingletonHandle();
            }
            catch (Exception ex)
            {
                
                Console.WriteLine(ex.ToString());
            }

        }
    }

    /// <summary>
    /// The following class will behave as singleton
    /// </summary>
    class MySingleton
    {
        // The following is a static variable which
        // will be used to keep the track that instance
        // of this class is created or not.
        private static bool IsAlreadyCreated = false;
        /// <summary>
        /// Constructor of the class. It is declared private
        /// so no one would be able to create the instance of
        /// this class.
        /// </summary>
        private MySingleton()
        {
            // I declared it private so now no one
            // would be able to create the instance
            // this class

        }
        /// <summary>
        /// It is static method. I declared it static, because
        /// I have designed the class in such a way that the
        /// instance of this class can not be created. And We know
        /// that static method can be accessed without declaring
        /// the instance of the class.
        /// This method will check the static boolean variable which
        /// we declared in the class. If the boolean variable is false
        /// then It will return the instance of the LogError class.
        /// Else if will return null
        /// </summary>
        /// <returns></returns>
        public static MySingleton GetSingletonHandle()
        {
            if (!IsAlreadyCreated)
            {
                IsAlreadyCreated = true;
                return new MySingleton();
            }
            else
            {
                throw new MyException("Get last, I can not give you more than one handle");
            }
        }
    }

    public class MyException : Exception
    {
        //new exception type for singleton classes
        public MyException(string s)
            : base(s)
        {
        }
    }
}




In the main program I tried to get the GetSingletonHandle() two times. first time it gave me the handle and the second time I got the exception. the screen shot of the out put is given below:




 
 
 If you are giving interview somewhere then the above explanation is good enough to show that you actually know about the singleton, but there are some issue which still needs to be covered. i.e.
 
  • What if two threads called the singleton at the same time? Well, the answer is that the two threads could create more than one instance of the class. How to overcome this issue? There are different ways to handle this issue. The first one is that make the  GetSingletonHandle() synchronized.
If you are discussing singleton with some one then they might ask you that what is Lazy instantiation and what is eager instantiation. 
The approach which we used in our singleton is called the lazy instantiation whic is "create the instance if it does not exists".
 
Eager instantiation is another apprach for implementing the singleton design pattern. In eager instantiation we create the singleton instance in a static initilizer. This is guaranted to be thread safe. So If I want to change my class to implement the eager then I will follow the following steps:
 
  •  Declare the static varible of the type singleton class (In my case it is MySingleton) and initilize it in the class. i.e.
           private static MySingleton mySingleton = new MySingleton ();
  • Now change the  GetSingletonHandle()  like this:
        public static MySingleton GetSingletonHandle()
        {
            return
mySingleton ;
        }

         
That is it. Now we have implemented the Singleton pattern using the eager instantiation.
 
You can change the singleton class according to the requirments but the bottom line is that singleton class is a class which have one and only one instance.Now its upto you that how do u ensure it in your domain and according to your requirments.
 
Regards,
Shahid riaz bhatti
Microsoft certified professional

Program.cs (2.54 kb)



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

Oct 19

Abstract Factory pattern

C# | Design Patterns 46 Comments »

Currently rated 3.0 by 1 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Abstract Factory Method:

 

Abstract factory method created the object of related classes or dependent classes without specifying their concrete class. 

 

Gang of four (GoF) defination:

 

According to the Gof the abstract factory pattern provide an interface for creating families of related or dependent objects without specifying their concrete classes. 

 

Where to use it:

Abstract factory method can be used in the following scenarios:

  • When a system should be independent of how its products are created, composed, and represented.
  • A class can not anticipate the class of object it must create
  • A system must use just one of a set of families of product.

Advantage:

One of the main advantages of Abstract Factory Pattern is that it isolates the concrete classes that are generated. The names of actual implementing classes are not needed to be known at the client side. Because of the isolation, you can change the implementation from one factory to another.


Example:

I am giving a very simple example. When I was studying C++ in college then our teacher taught us a concept of polymorphism by giving a very simple example. btw the polymorphism is that " The same function call behaves differently on every call"..I practically implemented polymorphism in C++ by using function overrding and inheritance. The assignment was that We have a living things all around us which includes human being, plant etc. Human beings can walk but the plant can not walk. So to solve this problem I made a c++ example in which I made an abstract class of Living thing and then inherited two class from it (i.e. Plant and Human being). Then I override the CanWalk method of the abstract class in the child classes with their own body.

 

Today I will take the same example for the abstract factory method. My code of the abstract factory method is given below and also the .cs file is attached at the end of this post.

using System;

namespace Shahid
{
    // MainApp test application

    class MainApp
    {
        public static void Main()
        {

            LivingFactory factory = new ConcreteLiving1();
            Client c1 = new Client(factory);
            c1.Run();

            LivingFactory factory2 = new ConcreteLiving2();
            Client c2 = new Client(factory2);
            c2.Run();


        }
    }

    // "AbstractFactory whicg is Living Factory"

    abstract class LivingFactory
    {
        public abstract AbstractLivingAnimal CreateLivingAnimal();
        public abstract AbstractLivingPlant CreateLivingPlant();
    }

    // "ConcreteLiving1"

    class ConcreteLiving1 : LivingFactory
    {
        public override AbstractLivingAnimal CreateLivingAnimal()
        {
            return new LivingAnimal1();
        }
        public override AbstractLivingPlant CreateLivingPlant()
        {
            return new LivingPlant1();
        }
    }

    // "ConcreteLiving2"

    class ConcreteLiving2 : LivingFactory
    {
        public override AbstractLivingAnimal CreateLivingAnimal()
        {
            return new LivingAnimal2();
        }
        public override AbstractLivingPlant CreateLivingPlant()
        {
            return new LivingPlant2();
        }
    }

    // "Abstract Living Animal

    abstract class AbstractLivingAnimal
    {
        public abstract void CanWalk(AbstractLivingPlant plant);
    }

    // "AbstractLiving plant"

    abstract class AbstractLivingPlant
    {
        
    }

    // "Living Animal 1"

    class LivingAnimal1 : AbstractLivingAnimal
    {

        public override void CanWalk(AbstractLivingPlant plant)
        {
            Console.WriteLine(this.GetType().Name + " can walk but " + plant.GetType().Name + " can not");
        }
    }

    // "Living Plant 1"

    class LivingPlant1 : AbstractLivingPlant
    {
      
    }

    class LivingAnimal2 : AbstractLivingAnimal
    {

        public override void CanWalk(AbstractLivingPlant plant)
        {
            Console.WriteLine(this.GetType().Name + " can walk but " + plant.GetType().Name + " can not");
        }
    }

    // "Living plant 2"

    class LivingPlant2 : AbstractLivingPlant
    {
        
    }
    // "Client" - the client code

    class Client
    {
        private AbstractLivingAnimal Animal;
        private AbstractLivingPlant Plant;

        // Constructor
        public Client(LivingFactory livingThing)
        {
            Animal = livingThing.CreateLivingAnimal();
            Plant = livingThing.CreateLivingPlant();
        }

        public void Run()
        {
              Animal.CanWalk(Plant);
        }
    }
}

 
In the above example we can see that in the main program we didn't called the LivingAnimal1,LivingAnimal2,LivingPlant1 and LivingPlant3 class directly. The code is given below:

            LivingFactory factory = new ConcreteLiving1();
            Client c1 = new Client(factory);
            c1.Run();

            LivingFactory factory2 = new ConcreteLiving2();
            Client c2 = new Client(factory2);
            c2.Run();

In the above code you can see that we have created the instance of an abstract class LivingFactory and instantiated it by the ConcreteLiving1 class. In the code you can see that the ConcreteLiving class is inherited from the abstract class LivingFactory. Then in the next line we created the object of the Client class and then called the Run method of the Client class. The Client's constructor take the parameter of Type LivingFactory and produces the output according to the parameter passed to it. But in the main program we dont know that what will be the out put of Client.Run(). Also if your business logic changes then you can change theimplementation of the Factory classes witout affecting the client side code.

In the example we can see that our main program is independent that how the LivingAnimal1,LivingAnimal2,LivingPlant1 and LivingPlant2 are created and composed.

 


 

Regards,

Shahid Riaz Bhatti

Microsoft certified professional

Program.cs (2.86 kb)



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

Oct 04

Facade design pattern using C#

C# | Design Patterns | General | Tips and Tricks 34 Comments »

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Dictionary Meaning : The front of a building

In Programming :

According to the Gang of four (GoF): "It is a design pattern that provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. "

Explanation:

So according to the GoF defination of the facade pattern we can say that facade pattern is used to wrap a set of complex classes into a simpler enclosing interface. It means that instead of calling the subsystem directly the developer has to use the unified simpler interface(facade class).

 

A Sample Program:
I have attached a rar file. Please read that file. I am also pasting that class, but for the better readability please download the attached rar file.
 
#region Start Facade
    /// <summary>
    /// In this example there are two classes which are:
    /// 1) Teacher
    /// 2) Student
    /// These two classes are our sub system.
    /// According to the defination of facade design pattern
    /// which is given below:
    /// (It is a design pattern that provide a unified interface
    ///  to a set of interfaces in a subsystem.)
    ///  So now according to the defination we have to create a unified
    ///  interface which would be class. You can find this class at the
    ///  end. i.e. after the student class.
    ///  This unified class will interact
    ///  with the sub system. In our main program we have to use this
    ///  unified class to access our subsystem instead of calling these
    ///  two subsystem directly.
    /// </summary>
    #endregion

    /// <summary>
    /// This is our Teacher class (Sub System). In this class we declared
    /// TeacherCollection variable of type List. In the constructor we
    /// initilized this TeacherCollection varible.
    /// Then we made a function called _GetAllTeacher of type List<T>.
    /// In this function we populated TeacherCollection with some dummy values.
    /// </summary>  
    public class Teacher
    {
        List<string> TeacherCollection;
        public Teacher()
        {
            TeacherCollection = new List<string>();
        }
        public List<string> _GetAllTeacher()
        {
            TeacherCollection.AddRange(new string[] {"Teacher One","Teacher Two","Teacher three","Teacher four","Teacher Five"});
            return TeacherCollection;
        }
    }
    /// <summary>
    /// This is our student class (Sub System). In this class we declared
    /// StudentCollection variable of type List. In the constructor we
    /// initilized this StudentCollection varible.
    /// Then we made a function called _GetAllStudent of type List<T>.
    /// In this function we populated StudentCollection with some dummy values.
    /// </summary>
    public class Student
    {
        List<string> StudentCollection;
        public Student()
        {
            StudentCollection = new List<string>();
        }
        public List<string> _GetAllStudent()
        {
            StudentCollection.AddRange(new string[] { "Student One", "Student Two", "Student three", "Student four", "Student Five" });
            return StudentCollection;
        }
    }

    /// <summary>
    ///
    /// </summary>
    public class Facade
    {
        // Declare the object of Subsystems
        Teacher _ObjectOfTeacher;
        Student _ObjectOfStudent;
        //Constructor
        public Facade()
        {
            // Initilize the Sub Systems.
            _ObjectOfTeacher = new Teacher();
            _ObjectOfStudent = new Student();
        }
        /// <summary>
        /// Get all teachers from the teacher Sub system
        /// </summary>
        /// <returns></returns>
        public List<string> GetTeacehrs()
        {
            return _ObjectOfTeacher._GetAllTeacher();
        }
        /// <summary>
        /// Get all students from Student Sub Systems
        /// </summary>
        /// <returns></returns>
        public List<string> GetStudents()
        {
            return _ObjectOfStudent._GetAllStudent();
        }
    }
 
Advantages of using Facade: 

The Facade pattern shields clients from complex subsystem components and provides a simpler programming interface for the general user. The Facade allows us to make changes in the underlying sub systems without requiring changes in the client code and reduces the compilation dependencies. 

 

Regards,

Shahid Riaz Bhatti

Microsoft Certified Application developer (MCAD)

Facaderar.rar (1.41 kb)



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags: , , , , ,