Thursday, January 17, 2008

General C#

General

Collections in C#

To construct and manipulate a collection of objects, .Net framework has provided us with many classes. ArrayList, BitArray, HashTable, SortedList, Queue and Stack are some of them. They are all included in System.Collections namespace.

ArrayList

The main problem of traditional arrays is that their size is fixed by the number you specify when declaring the array variable: you cannot add items beyond the specified dimension. Another limitation is that you cannot insert an item inside the list. To overcome this, you can create a linked list. Instead of working from scratch, the .NET Framework provides the ArrayList class. With the ArrayList class, you can add new items to a list, insert items inside a list, arrange items of a list, check the existence of an item in a list, remove an item from the list, inquire about the list, or destroy the list. These operations are possible through various properties and methods.

Hashtable

The System.Collections namespace provides a Hashtable container. A Hashtable represents a key/value pair in which the key is used for fast lookup.

BitArray


The BitArray class supports a collection of bits which are represented as Booleans. Because it stores bits rather than objects, BitArray has capabilities different from those of the other collections. However it still supports the basic collection underpinning by implementing ICollection and IEnumerable. It also implements ICloneable.

Design Patterns

A design pattern is a solution for a common problem or issue. Design patterns are often associated with object-oriented programming, but they are not exclusive to it. In fact, even non-computing disciplines have concepts similar to design patterns, which is likely from where the programming community borrowed the concept.

A design pattern does not imply that only one solution to the problem exists, nor is it necessarily the best solution in all cases. Patterns merely provide a best-practice approach to a particular problem, learned from the countless experiences of the programming community. A pattern often has several variations. Each programmer must determine if and when to apply a particular pattern. Often, the programming environment in use influences the pattern choice. Not all programming environments and languages support all design patterns. What may be easy to create in one environment or language may be extremely difficult in another.

Patterns focus on many types of problems. Related patterns are grouped together and assigned a type. This helps programmers identify similar types and it simplifies the process of comparing similar patterns to find the appropriate one(s) to utilize. One such grouping is the creational design patterns: patterns focused on creating instances of objects. A class represents the definition of an object. An instance of an object is where the object/class has been created in memory, which in many languages is commonly done using the new keyword. This process is often referred to simply as instantiation.

The FCL (Framework Class Library) builds on the strengths of Microsoft's experience with developing software libraries, one can assume that instances of design patterns found in the FCL are fairly appropriate usages of these patterns.

Singleton Design Pattern

The singleton design pattern is focused on having one—and only one—instance of an object. It instills encapsulated control of the object from a common place. An example is a directory service. The directory may contain multiple types of entries, but you want only one instance of the actual directory through which all information is accessed and controlled.

Limit an Object to a Single Instance

When thinking about limiting an object to a single instance, the C# keyword static immediately comes to mind. A common misperception is that assigning static to the class will easily solve the problem. In actuality, because static cannot be applied at the class level, the solution is more complex. You must rely on the use of static within the class to create the desired behavior.

The first step is to create a class with a static member field and/or property to contain your internally stored data. The type of data you use dictates the field/property data type. An ArrayList or Hashtable is a common choice because it allows a dynamic number of objects to be stored and manipulated.

Next, prevent the object from being directly created by making all constructors private. This will allow you to restrict creation of all instances through a single method.

Finally, provide a static method for controlling access to your single instance.

Singleton Sample Code

The following sample code depicts how to implement the singleton design pattern in C#. It utilizes a GetInstance() static method to control a reference to the single instance of the class:

using System;
namespace CodeGuru.DesignPattern
{
   /// 
   /// Class to demonstrate the use of the singleton design pattern.
   /// 
   public class SingletonExample
   {
      /// Internal singleton instance
      private static SingletonExample _Singleton;
 
      /// 
      /// Constructor to keep the class from being publicly instantiated.
      /// 
      private SingletonExample()
      {
      }
 
      /// 
      /// Control access to a single instance of the class.
      /// 
      /// 
      public static SingletonExample GetInstance()
      {
         if( _Singleton == null )
         {
            _Singleton = new SingletonExample();
         }
         return _Singleton;
      }
 
      /// 
      /// Use the instance to get some random data.
      /// 
      /// Random data fetched from the instance.
      public int GetRandomInstanceData()
      {
         Random random = new Random();
         return random.Next();
      }
   }
}

Factory design pattern

A detailed description of the Factory Method design pattern can be found elsewhere, so I will not try to describe it here. Suffice it to say that this pattern consists of two class hierarchies, one of Products, and one of Creators. Each ConcreteCreator class creates instances of specific ConcreteProduct classes using a factory method.

Factory methods are sometimes a more flexible way to instantiate a class than directly calling the constructor of the class, for the following reasons:

  • Unlike constructors, factory methods are not required to create a new object each time they are invoked. Factory methods can encapsulate the logic required to return a singleton instance of the class requested, or they can return an instance of the requested class from a pool of instances.
  • Factory methods can return any subtype of the type requested, and can require that clients refer to the returned object by its interface, rather than the implementation class. This enables an API to return objects without making their classes public.
  • The class for the object returned by a factory method need not even exist at the time the factory method is written. This is one of the classic benefits of polymorphism: "old code uses new code," which means that new classes can be added, and their instances returned by the factory method, without changing any of the existing code.

Builder Pattern

In Builder Pattern the user is given the choice to create the type of object he wants but the construction process is the same.

We consider an example suppose you went to buy a car. First you will choose the model of the car and then it's color and you consider it's price that whether it's feasible for you or not and if you want some extra luxuries in the car you will note them down as well and in the end you will place the order. Now you are isolated with the manufacturing process. You are not bothered by the manufacturing process it's the duty of the company because they have the assembly plant, which is programmed to manufacture cars of the model you choose and the manufacturing process is same for a specified model of car.

In Builder the client instructs the builder class on how to create the object and then asks it for the result. How the class is put together is up to the Builder class.

IBuilder Interface

using System;
using System.Windows.Forms;  
namespace BuilderPattern
{
            /// 
            /// Summary description for IBuilder.
            /// 
            public interface IBuilder
            {                       
                        void MnaufactureCar();
            }
}



Classes that extends from IBuilder interface

1) SuzukiMehran Class

using System;
using System.Windows.Forms;  
 
namespace BuilderPattern
{
            /// 
            /// Summary description for SuzukiMehran.
            /// 
            public class SuzukiMehran:IBuilder
            {
                        public void MnaufactureCar()
                        {
           MessageBox.Show("Suzuki Mehran Model 2002 "
                                                     +"Color Balck "
                                                     + "Air Conditioned " ); 
                        }
            }
}



2) SuzukiKhyber Class

     using System;
     using System.Windows.Forms;  
 
     namespace BuilderPattern
     {
              /// 
              /// Summary description for SuzukiKhyber.
              /// 
              public class SuzukiKhyber:IBuilder
              {
                        public SuzukiKhyber()
                        {                                   
                        }
 
                        public void MnaufactureCar()
                        {
                                     MessageBox.Show("Suzuki Khyber Model 2002 Standard "
                                                 +"Color Red "
                                                 +"Air Conditioned "
                                                 +"Alloy Rim "); 
                        }
               }
     }


Director class

using System;
 
namespace BuilderPattern
{
            /// 
            /// Summary description for Director.
            /// 
            public class Director
            {
                        public void ConstructCar(IBuilder build)
                        {
                                     build.MnaufactureCar(); 
                        }
            }
}


Client Class

private void button1_Click(object sender, System.EventArgs e)
{
            if(cmbChooseCar.Text=="Suzuki Mehran")
                         {
        Director car=new Director();
        IBuilder build=new SuzukiMehran();
        car.ConstructCar(build);  
             }
 
            if(cmbChooseCar.Text=="Suzuki Khyber")
             {
                        Director car=new Director();
                        IBuilder build=new SuzukiKhyber(); 
                        car.ConstructCar(build);  
             }
}



Description of program

The above program contains an interface IBuilder which declare one function ManufactureCar. Two classes SuzukiMehran and SuzukiKhyber implement this interface IBuilder and also implements the interface function ManufactureCar. Now we have a Director class which contains a method Constructcar which accepts an argument of type IBuilder and then call Manufacturecar method of any one Class depending upon the reference type variable build that which type of object of its child class it is pointing. The Client class just decides what type of object to create either SuzukiMehran or SuzukiKhyber and then pass this object as an argument to director method ManufactureCar.

0 Comments: