Tuesday, March 31, 2009

Design Patterns :: Singleton

Design Patterns :: Singleton

There are many common situations when singleton pattern is used:
 - Accesing resources in shared mode
 - Configuration Classes
 - Logger Classes
 - Serialization
 - Network Port Interface

Singleton Design Pattern
Singleton Design Pattern

Check list
1.Define a private static attribute in the "single instance" class.
2.Define a public static accessor function in the class.
3.Do "lazy initialization" (creation on first use) in the accessor function.
4.Define all constructors to be protected or private.
5.Clients may only use the accessor function to manipulate the Singleton.



  1. using System;

  2. namespace DesignPatternsSingleton
  3. {
  4.   /// <summary>
  5.   /// MainApp startup class for Design Patterns :: Singleton
  6.   /// </summary>
  7.   class MainApp
  8.   {
  9.   /// <summary>
  10.   /// The Singleton class.
  11.   /// </summary>
  12.   public class Singleton
  13.   {
  14.     private static Singleton _instance;

  15.     // Constructor is 'protected'
  16.     protected Singleton()
  17.     {
  18.     }

  19.     public static Singleton Instance()
  20.     {
  21.       // Uses lazy initialization.
  22.       // Note: this is not thread safe.
  23.       if (_instance == null)
  24.       {
  25.         _instance = new Singleton();
  26.       }

  27.       return _instance;
  28.     }
  29.   }
  30. }

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;

  4. namespace DesignPatternsSingleton
  5. {
  6.   /// <summary>
  7.   /// MainApp startup class for Real-World
  8.   /// Singleton Design Pattern.
  9.   /// </summary>
  10.   class MainApp
  11.   {
  12.     /// <summary>
  13.     /// Entry point into console application.
  14.     /// </summary>
  15.     static void Main()
  16.     {
  17.       LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
  18.       LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
  19.       LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
  20.       LoadBalancer b4 = LoadBalancer.GetLoadBalancer();

  21.       // Same instance?
  22.       if (b1 == b2 && b2 == b3 && b3 == b4)
  23.       {
  24.         Console.WriteLine("Same instance\n");
  25.       }

  26.       // Load balance 15 server requests
  27.       LoadBalancer balancer = LoadBalancer.GetLoadBalancer();
  28.       for (int i = 0; i < 15; i++)
  29.       {
  30.         string server = balancer.Server;
  31.         Console.WriteLine("Dispatch Request to: " + server);
  32.       }

  33.       // Wait for user
  34.       Console.ReadKey();
  35.     }
  36.   }

  37.   /// <summary>
  38.   /// The 'Singleton' class
  39.   /// </summary>
  40.   class LoadBalancer
  41.   {
  42.     private static LoadBalancer _instance;
  43.     private List<string> _servers = new List<string>();
  44.     private Random _random = new Random();

  45.     // Lock synchronization object
  46.     private static object syncLock = new object();

  47.     // Constructor (protected)
  48.     protected LoadBalancer()
  49.     {
  50.       // List of available servers
  51.       _servers.Add("ServerI");
  52.       _servers.Add("ServerII");
  53.       _servers.Add("ServerIII");
  54.       _servers.Add("ServerIV");
  55.       _servers.Add("ServerV");
  56.     }

  57.     public static LoadBalancer GetLoadBalancer()
  58.     {
  59.       // Support multithreaded applications through
  60.       // 'Double checked locking' pattern which (once
  61.       // the instance exists) avoids locking each
  62.       // time the method is invoked
  63.       if (_instance == null)
  64.       {
  65.         lock (syncLock)
  66.         {
  67.           if (_instance == null)
  68.           {
  69.             _instance = new LoadBalancer();
  70.           }
  71.         }
  72.       }

  73.       return _instance;
  74.     }

  75.     // Simple, but effective random load balancer
  76.     public string Server
  77.     {
  78.       get
  79.       {
  80.         int r = _random.Next(_servers.Count);
  81.         return _servers[r].ToString();
  82.       }
  83.     }
  84.   }
  85. }

Setting Language/Culture in Using Global Resource Files



Setting Language/Culture in Using Global Resource Files


In this short post, in the code of an aspx page, we want to make the page to use our global resource file called UI.fr-CA.resx that is in Canadian French (fr-CA).

In order to this, just open the source code of the page (or the source code of the super class of your page class) and override its InitializeCulture method as in the following:

protected override void InitializeCulture()
{
Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("fr-CA");
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("fr-CA");
base.InitializeCulture();
}



There is a good point in the above code: it works even if your controls or user controls located in the page have processes in threads different from the current thread!

Wednesday, March 18, 2009

Creational Design Patterns

List of Creational Design Patterns

In the following, which five design patterns are the creational patterns?


 1) Abstract Factory
 2) Adapter
 3) Bridge
 4) Builder
 5) Chain of Responsibility
 6) Command
 7) Composite
 8) Decorator
 9) Facade
10) Factory Method
11) Flyweight
12) Interpreter
13) Iterator
14) Mediator
15) Memento
16) Observer
17) Prototype
18) Proxy
19) Singleton
20) State
21) Strategy
22) Template Method
23) Visitor
 


Creational Design Patterns


  1. Abstract Factory
  2. Builder
  3. Factory Method
  4. Prototype
  5. Singleton

Object Initializers with Anonymous Types



Object Initializers with Anonymous Types




In C# 3.0, we can use object initializers with anonymous types. The following example shows how it can be done:

The Customer class is an arbitrary class that we want to use in this example:


public class Customer
{
public int CustomerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}


We declare a colloecton of customers by employing "object initializers":


List customers = new List
{
new Customer { CustomerID = 99, FirstName = "Brian" , LastName = "White"},
new Customer { CustomerID = 100, FirstName = "Nicole" , LastName = "Stewart"},
new Customer { CustomerID = 101, FirstName = "Lucy" , LastName = "Brothers"}
};

Now, we create a LINQ query where the returning objects have anonymous types; an anonymous type that has two properties: ID and Name; and also we employ the object initializer concept to initialize the properties of our objects:


var selCust = from c in customers
where c.CustomerID <= 100
orderby c.LastName, c.FirstName
select new { ID = c.CustomerID, Name = c.FirstName + " " + c.LastName};


The variable selCust contains objects of an anonymous type with their properties already set (initialized). To confirm this, run the following code snippet:


foreach (var cust in selCust)
{
Console.WriteLine(cust.ID.ToString() + " " + cust.Name);
}