Showing posts with label Design Patern. Show all posts
Showing posts with label Design Patern. Show all posts

Wednesday, July 2, 2008

Can you describe IUKNOWN interface in short?

Every COM object supports at least one interface, the IUnknown interface. All interfaces are classes derived from the base class IUnknown. Each interface supports methods access data and performs operations transparently to the programmer. For example, IUnknown supports three methods, AddRef, Release (), and QueryInterface(). Suppose that printerf is a pointer to an IUnknown. Printerf->;AddRef() increments the reference count. Printerf->;Release() decrements the reference count, deleting the object when the reference count reaches zero. Printerf->;QueryInterface(IDesired, pDesired) checks to see if the current interface (IUnknown) supports snother interface, IDesired, creates an instance (via a call to CoCreateInstance()) of the object if the reference count is zero (the object does not yet exist), and then calls pDesired->;AddRef() to increment the reference count (where pDesired is a pointer to IDesired) and returns the pointer to the caller.

What is Reference counting in COM?

Reference counting is a memory management technique used to count how many times an object has a pointer referring to it. The first time is it created; the reference count is set to one. When the last reference to the object is nulled, the reference count is set to zero and the object is deleted. Care must be exercised to prevent a context switch from changing the reference count at the time of deletion.

Thursday, December 6, 2007

Chain of Responsbility design pattern

Hi all,

I got a good article on Chain of Responsbility design pattern from here. the extract of it as ::::::

Introduction
A powerful design pattern geared towards handling an event is the Chain of Responsbility design pattern. This pattern helps decouple related algorithms in C# ASP .NET and can help your software become more scalable and easier to control.

In general, the Chain of Responsbility design pattern allows you to link together a serious of classes or algorithms in a hierarchy and pass a command (preferably a Command pattern object) into the mix to get handled by one of the members of the chain. One of the benefits of this design pattern is, not having to know the details of the members in the chain. You simply pass the command into the chain. Each class will attempt to handle the request until all classes have been used. While it is possible for a request to go unhandled, this is a powerful design pattern when used appropriately.

Two Ways to Make a Chain
As with all first programming examples, the Hello World example is a good introduction to an implementation of the Chain of Responsbility design pattern in C# ASP .NET. However, first let's take a look at the standard way of handling a request without using the Chain of Responsbility.

Standard Method of Handling a Request

void main()
{
Command MyRequest = new Command();
if (Handler1(MyRequest) == true)
{
return;
}
else if (Handler2(MyRequest) == true)
{
return;
}
else if (Handler3(MyRequest) == true)
{
return;
}
}

As you can see in the above example, to handle MyRequest we pass it to each Handler function that we've defined. There are several drawbacks to this simplistic method, especially in an object oriented language such as C# .NET. Foremost, there are many conditionals which create confusion when reading the code. This can especially become a problem when performing team development and debugging. More importantly, detailed knowledge of the handler implementations are required since they are listed within the conditional.
The above example can be enhanced with a Chain of Responsbility as shown in the following example:

void main()
{
Command MyRequest = new Command();
Handler MyHandler1 = new Handler1();
Handler MyHandler2 = new Handler2();
Handler MyHandler3 = new Handler3();

MyHandler1.SetSuccessor(MyHandler2);
MyHandler2.SetSuccessor(MyHandler3);

MyHandler1.HandleRequest(MyRequest);
}

In this example, we have implemented a Chain of Responsiblity design pattern with C# ASP .NET which handles the request. After setting up the initial chain, we only need to pass MyRequest to the first handler (which is of the generic type 'Handler'). Knowledge of which handler gets called next is preserved within the chain itself.

Say Hello to the Chain
By following the above example for implementing a Chain of Responsibility, we can apply it to create a simple Hello World example as shown in the following code.

static void Main(string[] args)
{
Handler MyEnglishHandler = new EnglishHandler();
Handler MyFrenchHandler = new FrenchHandler();
Handler MySpanishHandler = new SpanishHandler();
// Setup the chain of responsibility.
MyEnglishHandler.SetSuccessor(MyFrenchHandler);
MyFrenchHandler.SetSuccessor(MySpanishHandler);
// Throw the first handler a request and then throw two more for fun.
MyEnglishHandler.HandleRequest("en-US Hello World");
MyEnglishHandler.HandleRequest("es-US Hola Mundo");
MyEnglishHandler.HandleRequest("fr-FR Bonjour Monde");
Console.ReadKey();
}

Output:
Handled by EnglishHandler: Hello World
Dirigido por SpanishHandler: Hola Mundo
Manipule pres FrenchHandler: Bonjour Monde

Notice that there will be three handlers, an English, a French, and a Spanish handler. The command request will consist of two parts: a culture indicator and the text to display. For this example, a simple string was used in place of a Command design pattern. The culture indicator is just the first 5 characters of the string. Each handler will look at the culture indicator to determine whether it should handle the printing of the text to the console. If the handler can not handle the command, it passes it to the next handler in the chain, until all handlers have been ran.

To get to the meat of the Chain of Responsibility, we need to define the generic class that our Handlers will inherit from.
The Handler Class
We have chosen to use an abstract class in place of an interface for implementing the generic Handler class. This is due to the fact that our Handler class will implement the body of one of the functions as well as define a protected member. Also note that abstract classes, in general, perform faster than interfaces due to less memory lookups.

abstract class Handler
{
protected Handler successor;
public Handler()
{
}

public void SetSuccessor(Handler aSuccessor)
{
successor = aSuccessor;
}
public abstract void HandleRequest(string strRequest);
}

This Handler definition is fairly simple. The most important part is the inclusion of a protected successor object, of type Handler. This allows a form of a linked list to implement our chain. We also implement a SetSuccessor function to assign the successor. The HandleRequest function will be required by all handlers to initiate a possible action.

Creating a Concrete Handler
Now that we have the abstract class Handler defined, we can now create some concrete handlers to create a complete Chain of Responsibility in C# ASP .NET. Our first handler will handle English strings by looking in the command for the culture identifier "en-us".

The EnglishHandler Class
class EnglishHandler : Handler
{
private const string LANGUAGE_TAG = "en-us";
public override void HandleRequest(string strRequest)
{
int iStart = strRequest.ToLower().IndexOf(LANGUAGE_TAG);
if (iStart > -1)
{
string strResponse = strRequest.Substring(iStart + LANGUAGE_TAG.Length, strRequest.Length - (iStart + LANGUAGE_TAG.Length));
Console.WriteLine("Handled by EnglishHandler:" + strResponse);
}
else if (successor != null)
{
successor.HandleRequest(strRequest);
}
}
}

Notice our handler inherits from our abstract base class Handler and defines the required HandleRequest function. The body of the function simply checks the first 5 characters of the command string to see if it contains "en-us". If it does, the payload portion of the string is printed to the console, the command is deemed handled, and execution of the chain stops. If "en-us" is not found, the handler passes the command to the next handler in line. Of course, if no other handler exists, the command remains unhandled. Unhandled commands could be managed as well by including additional detection code.

We can create two more handlers to make the example more interesting, as follows.

The FrenchHandler Class

class FrenchHandler : Handler
{
private const string LANGUAGE_TAG = "fr-fr";
public override void HandleRequest(string strRequest)
{
int iStart = strRequest.ToLower().IndexOf(LANGUAGE_TAG);
if (iStart > -1)
{
string strResponse = strRequest.Substring(iStart + LANGUAGE_TAG.Length, strRequest.Length - (iStart + LANGUAGE_TAG.Length));
strResponse = "Manipulé près FrenchHandler:" + strResponse;
Console.WriteLine(strResponse);
}
else if (successor != null)
{
successor.HandleRequest(strRequest);
}
}
}

Note, the FrenchHandler differs only by the culture identifier that it is looking for and by the action performed on the payload. Just like the EnglishHandler, the FrenchHandler passes the command to the next in line if it fails to handle it. The FrenchHandler doesn't need to know the details about its successor, only that it's of type Handler.

The SpanishHandler Class

class SpanishHandler : Handler
{
private const string LANGUAGE_TAG = "es-us";
public override void HandleRequest(string strRequest)
{
int iStart = strRequest.ToLower().IndexOf(LANGUAGE_TAG);
if (iStart > -1)
{
string strResponse = strRequest.Substring(iStart + LANGUAGE_TAG.Length, strRequest.Length - (iStart + LANGUAGE_TAG.Length));
Console.WriteLine("Dirigido por SpanishHandler:" + strResponse);
}
else if (successor != null)
{
successor.HandleRequest(strRequest);
}
}
}

Now that we have created 3 handlers, our original main code can be executed. We begin by defining three handlers of each concrete handler type. We then setup the chain in our desired order. Typically, order doesn't matter since each handler will have a chance at the request. However, speed issues may arise where order becomes critical. Finally, we send a request to the first member of the chain and the Chain of Responsibility handles the rest. Notice in the main program above that we execute 3 requests. Each one will be handled by one of the concrete handlers.

// Throw the first one a request.
MyEnglishHandler.HandleRequest("en-US Hello World");
MyEnglishHandler.HandleRequest("es-US Hola Mundo");
MyEnglishHandler.HandleRequest("fr-FR Bonjour Monde");

Since the concrete handlers inherit from the generic Handler class, they have no need to know the concrete details about their successors. This allows us to implement new concrete handlers (for other languages, for example), and insert them anywhere in the chain.

What about C# Multicast Delegates?
C# delegates can be a form of a chain of responsiblity in themselves. By creating a delegate and assigning it multiple functions for execution, a multicast delgate is created and may be used in a similar fashion to a chain of responsibility design pattern. When the delegate is invoked, each function added to the multicast delgate's chain is executed. Where a typical chain of responsiblity pattern will only continue executing handlers until one succeeds, the multicast delegate will always execute each handler. For example:

delegate void MyMulticastDelegate(int x, int y);
void main()
{
MyMulticastDelegate MyFunction = new MyMulticastDelegate(MyFunc1);
MyFunction += new MyMulticastDelegate(MyFucn2);
// Calling MyFunction will execute MyFunc1 and MyFunc2 in a chain.
MyFunction(10, 20);
}
static public void MyFunc1(int x, int y)
{
Console.WriteLine("MyFunc1");
}

static public void MyFunc2(int x, int y)
{
Console.WriteLine("MyFunc2");
}
Conclusion

The Chain of Responsibility design pattern helps you create more scalable and reusable code in C# ASP .NET. By defining concrete handlers inidividually, you help decouple algorithms into separate and reusable classes. A request can be passed to the first handler and executed by any member of the chain, regardless of whether those handlers, or their concrete types, are known beforehand. C# .NET provides mutlicast delegates which may be considered a form of a chain of responsibility. Developers can take advantage of multicast delegates to perform event and callback functionality or design their own chain of responsiblity pattern with C# ASP .NET.

PROTOTYPE PATTERN

The PROTOTYPE PATTERN comes under the classification of Creational Patterns. The creational patterns deals with the best way to create objects. This helps to copy or clone the existing objects to create new ones rather than creating from the scratch.

Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype. -- "Design Patterns" Gamma et al., Addison-Wesley, ISBN:0-201-63361-2"

The prototype pattern is used when creating an instance of a class is very time consuming or complex in some way. Then rather than creating more instances, it is possible to make copies of the original instances and modifying them as appropriate.

When we are not in a position to call a constructor for an object directly, we could alternatively clone a pre-existing object (a prototype) of the same class. When there are many subclasses that differ only in the kind of objects they create a Prototype Pattern can be used to reduce the number of subclasses by cloning a prototype. Prototype Design Pattern helps in reducing number of classes.

For example suppose we have to do say Sales Analysis on a set of data in the database. Normally we will create an object encapsulating this data and do the Sales Analysis. Suppose now we have to do another type of analysis say Promotion Analysis on the same data. Now instead of creating another object corresponds to the data from the scratch, we can clone the existing object and do the analysis. This is one of the classical use of prototype pattern.

Remember that in C#, this pattern can be implemented easily by using the clone(). Any class, which wants to support cloning, should inherit from the ICloneable interface in C#. ICloneable interface contains a Clone() method which we can override in our class. Clone can be implemented either as a deep copy or a shallow copy. In a deep copy, all objects are duplicated; whereas, in a shallow copy, only the top-level objects are duplicated and the lower levels contain references.
The resulting clone must be of the same type as or a compatible type to the original instance.

sample code in C#

This real-world code demonstrates the Prototype pattern in which new Color objects are created by copying pre-existing, user-defined Colors of the same type.

using System;
using System.Collections;
namespace PrototypePattern
{
// MainApp test application
class MainApp
{
static void Main()
{
ColorManager colormanager = new ColorManager();
// Initialize with standard colors
colormanager["red" ] = new Color(255, 0, 0);
colormanager["green"] = new Color( 0, 255, 0);
colormanager["blue" ] = new Color( 0, 0, 255);
// User adds personalized colors
colormanager["angry"] = new Color(255, 54, 0);
colormanager["peace"] = new Color(128, 211, 128);
colormanager["flame"] = new Color(211, 34, 20);
Color color;
// User uses selected colors
string name = "red";
color = colormanager[name].Clone() as Color;
name = "peace";
color = colormanager[name].Clone() as Color;
name = "flame";
color = colormanager[name].Clone() as Color;
// Wait for user
Console.Read();
}
}
// "Prototype"
abstract class ColorPrototype
{
public abstract ColorPrototype Clone();
}
// "ConcretePrototype"
class Color : ColorPrototype
{
private int red;
private int green;
private int blue;
// Constructor
public Color(int red, int green, int blue)
{
this.red = red;
this.green = green;
this.blue = blue;
}
// Create a shallow copy
public override
ColorPrototype Clone()
{
Console.WriteLine("Cloning color RGB: {0,3},{1,3},{2,3}",red, green, blue);
return this.MemberwiseClone() as ColorPrototype;
}
}
// Prototype manager
class ColorManager
{
Hashtable colors = new Hashtable();
// Indexer
public ColorPrototype this[string name]
{
get
{
return colors[name] as ColorPrototype;
}

set
{
colors.Add(name, value);
}
}
}
}


Output




Builder Pattern

Suppose you had a series of objects that needed constructed, but your application needs to specialize how they are built. This is where the builder pattern comes into play. It handles performing the building of the necessary objects (also referred as the "product"); the builder class has that sole responsibility. The builder class also supports inheritance, which the product that the builder creates is usually involved in the inheritance scheme, meaning that the derived builder objects are actually building their related product object.

The builder pattern has a director that oversees the build process. The director has a reference to the builder(s) available and is responsible for invoking the correct method(s) in the builder. The builder has a common interface that all builders derive from and that the director knows about, and because of this, it can easily do its job. Inheritance plays a key, as the builder's interface is abstract, and the derived builder classes actually do the work of building an object. The resulting class that it builds can make use of inheritance to provide a more specific implementation. The builder class would be responsible for invoking the correct object.

It is possible that the builder/director relationship be dynamically created through the use of a configuration file, though that adds a lot of work to the software development process. More simplistically and realistically, this relationship is statically created through a constructor or an initialization method.

Non-software Example
Fast food restaurants to construct children's meals use this pattern. Children's meals typically consist of a main item, a side item, a drink, and a toy (e.g., a hamburger, fries, Coke, and toy car). Note that there can be variation in the content of the children's meal, but the construction process is the same. Whether a customer orders a hamburger, cheeseburger, or chicken, the process is the same. The employee at the counter directs the crew to assemble a main item, side item, and toy. These items are then placed in a bag. The drink is placed in a cup and remains outside of the bag. This same process is used at competing restaurants. [Michael Duell, "Non-software examples of software design patterns", Object Magazine, Jul 97, p54]

Another example for Builder pattern is a Computer Assembly. A computer is nothing but the bundling of various components like FDD, HDD, Monitor etc. But when an user buys a computer someone assemble all these components and given to us. Remember that here the building process is completely hidden from the client or user.

Remember that a project can contain one or more builders and each builder is independent of others. This will improves the modularity and makes the addition of other builders relatively simple. Since each builder constructs the final product step by step, we have more control over the final product that a builder constructs.

C# implementation
This real-world code demonstates the Builder pattern in which different vehicles are assembled in a step-by-step fashion. The Shop uses VehicleBuilders to construct a variety of Vehicles in a series of sequential steps.

using System;
using System.Collections;

namespace BuilderPattern{
// MainApp test application
public class MainApp
{
public static void Main()
{
// Create shop with vehicle builders
Shop shop = new Shop();
VehicleBuilder b1 =
new ScooterBuilder();
VehicleBuilder b2 =
new CarBuilder();
VehicleBuilder b3 =
new MotorCycleBuilder();
// Construct and display vehicles
shop.Construct(b1);
b1.Vehicle.Show();

shop.Construct(b2);
b2.Vehicle.Show();

shop.Construct(b3);
b3.Vehicle.Show();
// Wait for user
Console.Read();
}
}
// "Director"

class Shop
{
// Builder uses a complex series of steps
public void Construct(VehicleBuilder vehicleBuilder)
{
vehicleBuilder.BuildFrame();
vehicleBuilder.BuildEngine();
vehicleBuilder.BuildWheels();
vehicleBuilder.BuildDoors();
}
}

// "Builder"

abstract class VehicleBuilder
{
protected Vehicle vehicle;

// Property
public Vehicle Vehicle
{
get{ return vehicle; }
}

public abstract void BuildFrame();
public abstract void BuildEngine();
public abstract void BuildWheels();
public abstract void BuildDoors();
}

// "ConcreteBuilder1"

class MotorCycleBuilder : VehicleBuilder
{
public override void BuildFrame()
{
vehicle =
new Vehicle("MotorCycle");
vehicle["frame"] = "MotorCycle Frame";
}

public override void BuildEngine()
{
vehicle["engine"] = "500 cc";
}

public override void BuildWheels()
{
vehicle["wheels"] = "2";
}

public override void BuildDoors()
{
vehicle["doors"] = "0";
}
}

// "ConcreteBuilder2"

class CarBuilder : VehicleBuilder
{
public override void BuildFrame()
{
vehicle =
new Vehicle("Car");
vehicle["frame"] = "Car Frame";
}

public override void BuildEngine()
{
vehicle["engine"] = "2500 cc";
}

public override void BuildWheels()
{
vehicle["wheels"] = "4";
}

public override void BuildDoors()
{
vehicle["doors"] = "4";
}
}

// "ConcreteBuilder3"

class ScooterBuilder : VehicleBuilder
{
public override void BuildFrame()
{
vehicle =
new Vehicle("Scooter");
vehicle["frame"] = "Scooter Frame";
}

public override void BuildEngine()
{
vehicle["engine"] = "50 cc";
}

public override void BuildWheels()
{
vehicle["wheels"] = "2";
}

public override void BuildDoors()
{
vehicle["doors"] = "0";
}
}

// "Product"

class Vehicle
{
private string type;
private Hashtable parts = new Hashtable();

// Constructor
public Vehicle(string type)
{
this.type = type;
}

// Indexer (i.e. smart array)
public object this[string key]
{
get{ return parts[key]; }
set{ parts[key] = value; }
}

public void Show()
{
Console.WriteLine("\n---------------------------");
Console.WriteLine("Vehicle Type: {0}", type);
Console.WriteLine(" Frame : {0}", parts["frame"]);
Console.WriteLine(" Engine : {0}", parts["engine"]);
Console.WriteLine(" #Wheels: {0}", parts["wheels"]);
Console.WriteLine(" #Doors : {0}", parts["doors"]);
}
}
Output

Non-Software Examples of Software Design Patterns

Hi all,

Today while browsing on the net Guess what I Got :::::
Something that let you grasp an idea of Software Design Patterns in a really simple and close to real world manner.

Follow the link and enjoy …………………

Non-Software Examples of Software Design Patterns by Michael Duell

Isn’t it really simple ..

Wednesday, December 5, 2007

The adapter pattern

The adapter pattern is easy to implement and makes it easier to connect to external data stores of varying types. It does not matter how the interfaces vary; you can easily create a common interface using the adapter pattern.
Using the adapter pattern makes interfacing with a variety of differing applications much easier. This pattern is especially useful when an application must connect to multiple external applications that differ in their requirements.
With a myriad of API's available in business systems, programs (like Microsoft Word), web services, etc., there are many different interfaces a developer has to understand to tie them all together into one business solution that he or she may be developing. For instance, maybe an application needs to connect to credit card service gateways to verify a customer's credit limit or to run a debit against the account. An application could connect to a health insurance provider to bill them for services provided. An application could display maps from varying map providers.

One thing that is certain with tying in various business systems is that the API's a developer uses will be different. There is not any standard interface across the industry for implementing a certain type of system, but there is good reason for you to want to do so. Uniformity in application development makes maintenance and documentation easier and makes the application design better.
However, with these varying systems, how can one tie together all of these interfaces into one common one? This is where the adapter pattern comes into play.


A very nice example I found here

Monday, December 3, 2007

Further Reading - Singleton Pattern

Further Reading

Please refer to the following links for more related information:

http://www.dofactory.com/Patterns/PatternSingleton.aspx
http://www.yoda.arachsys.com/csharp/singleton.html
http://aspalliance.com/810_Implementing_a_Singleton_Pattern_in_C

Implementing the Singleton Pattern in C#

In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. Sometimes it is generalized to systems that operate more efficiently when only one or a few objects exist. Essentially, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. Most commonly, singletons don't allow any parameters to be specified when creating the instance - as otherwise a second request for an instance but with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.) This article deals only with the situation where no parameters are required. Typically a requirement of singletons is that they are created lazily - i.e. that the instance isn't created until it is first needed.

How do we ensure that a class has only one instance and that the instance is easily accessible? A global variable makes an object accessible, but it doesn't keep you from instantiating multiple objects. A better solution is to make the class itself responsible for keeping track of its sole instance. The class can ensure that no other instance can be created (by intercepting requests to create new objects), and it can provide a way to access the instance. This is the Singleton pattern.

There are various different ways of implementing the singleton pattern in C#. I shall present them here in reverse order of elegance, starting with the most commonly seen, which is not thread-safe, and working up to a fully lazily-loaded, thread-safe, simple and highly performant version. Note that in the code here, I omit the private modifier, as it is the default for class members. In many other languages such as Java, there is a different default, and private should be used.
All these implementations share four common characteristics, however:

  • A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing - if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn't known until runtime.
  • The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.
  • A static variable which holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary.
Note that all of these implementations also use a public static property Instance as the means of accessing the instance. In all cases, the property could easily be converted to a method, with no impact on thread-safety or performance.
First version - not thread-safe
// Bad code! Do not use!
public sealed class Singleton
{
static Singleton instance=null;
Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}

As hinted at before, the above is not thread-safe. Two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn't guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.

Second version - simple thread-safety

public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
}

This implementation is thread-safe. The thread takes out a lock on a shared object, and then checks whether or not the instance has been created before creating the instance. This takes care of the memory barrier issue (as locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time - by the time the second thread enters it, the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is acquired every time the instance is requested.

Note that instead of locking on typeof(Singleton) as some versions of this implementation do, I lock on the value of a static variable which is private to the class. Locking on objects which other classes can access and lock on (such as the type) risks performance issues and even deadlocks. This is a general style preference of mine - wherever possible, only lock on objects specifically created for the purpose of locking, or which document that they are to be locked on for specific purposes (e.g. for waiting/pulsing a queue). Usually such objects should be private to the class they are used in. This helps to make writing thread-safe applications significantly easier.

Third version - attempted thread-safety using double-check locking

// Bad code! Do not use!
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance==null)
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}

This implementation attempts to be thread-safe without the necessity of taking out a lock every time. Unfortunately, there are four downsides to the pattern:

  • It doesn't work in Java. This may seem an odd thing to comment on, but it's worth knowing if you ever need the singleton pattern in Java, and C# programmers may well also be Java programmers. The Java memory model doesn't ensure that the constructor completes before the reference to the new object is assigned to instance. The Java memory model underwent a reworking for version 1.5, but double-check locking is still broken after this without a volatile variable (as in C#).
  • Without any memory barriers, it's broken in the ECMA CLI specification too. It's possible that under the .NET 2.0 memory model (which is stronger than the ECMA spec) it's safe, but I'd rather not rely on those stronger semantics, especially if there's any doubt as to the safety. Making the instance variable volatile can make it work, as would explicit memory barrier calls, although in the latter case even experts can't agree exactly which barriers are required. I tend to try to avoid situations where experts don't agree what's right and what's wrong!
  • It's easy to get wrong. The pattern needs to be pretty much exactly as above - any significant changes are likely to impact either performance or correctness.
  • It still doesn't perform as well as the later implementations.

Fourth version - not quite as lazy, but thread-safe without using locks

public sealed class Singleton
{
static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}

As you can see, this is really is extremely simple - but why is it thread-safe and how lazy is it? Well, static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain. Given that this check for the type being newly constructed needs to be executed whatever else happens, it will be faster than adding extra checking as in the previous examples. There are a couple of wrinkles, however:

  • It's not as lazy as the other implementations. In particular, if you have static members other than Instance, the first reference to those members will involve creating the instance. This is corrected in the next implementation.
  • There are complications if one static constructor invokes another which invokes the first again. Look in the .NET specifications (currently section 9.5.3 of partition II) for more details about the exact nature of type initializers - they're unlikely to bite you, but it's worth being aware of the consequences of static constructors which refer to each other in a cycle.
  • The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called beforefieldinit. Unfortunately, the C# compiler (as provided in the .NET 1.1 runtime, at least) marks all types which don't have a static constructor (i.e. a block which looks like a constructor but is marked static) as beforefieldinit.

· One shortcut you can take with this implementation (and only this one) is to just make instance a public static readonly variable, and get rid of the property entirely. This makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a property in case further action is needed in future, and JIT inlining is likely to make the performance identical. (Note that the static constructor itself is still required if you require laziness.)

Fifth version - fully lazy instantiation

public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}

Here, instantiation is triggered by the first reference to the static member of the nested class, which only occurs in Instance. This means the implementation is fully lazy, but has all the performance benefits of the previous ones. Note that although nested classes have access to the enclosing class's private members, the reverse is not true, hence the need for instance to be internal here. That doesn't raise any other problems, though, as the class itself is private. The code is a bit more complicated in order to make the instantiation lazy, however.

Performance vs laziness

In many cases, you won't actually require full laziness - unless your class initialization does something particularly time-consuming, or has some side-effect elsewhere, it's probably fine to leave out the explicit static constructor shown above. This can increase performance as it allows the JIT compiler to make a single check (for instance at the start of a method) to ensure that the type has been initialized, and then assume it from then on. If your singleton instance is referenced within a relatively tight loop, this can make a (relatively) significant performance difference. You should decide whether or not fully lazy instantiation is required, and document this decision appropriately within the class. (See below for more on performance, however.)

Exceptions

Sometimes, you need to do work in a singleton constructor which may throw an exception, but might not be fatal to the whole application. Potentially, your application may be able to fix the problem and want to try again. Using type initializers to construct the singleton becomes problematic at this stage. Different runtimes handle this case differently, but I don't know of any which do the desired thing (running the type initializer again), and even if one did, your code would be broken on other runtimes. To avoid these problems, I'd suggest using the second pattern listed on the page - just use a simple lock, and go through the check each time, building the instance in the method/property if it hasn't already been successfully built.

The content was originally posted at http://www.yoda.arachsys.com/csharp/singleton.html I copied it here just in case i the post disappears. My due regards to the original writers.

The Singleton pattern has several benefits:
1. Controlled access to sole instance. Because the Singleton class encapsulates its sole instance, itcan have strict control over how and when clients access it.
2. Reduced name space. The Singleton pattern is an improvement over global variables. It avoids polluting the name space with global variables that store sole instances.
3. Permits refinement of operations and representation. The Singleton class may be subclassed, and it's easy to configure an application with an instance of this extended class. You can configure the application with an instance of the class you need at run-time.
4. Permits a variable number of instances. The pattern makes it easy to change your mind and allow more than one instance of the Singleton class. Moreover, you can use the same approach to control the number of instances that the application uses. Only the operation that grants access to the Singleton instance needs to change.
5. More flexible than class operations. Another way to package a singleton's functionality is to use class operations (that is, static member functions in C++ or class methods in Smalltalk). But both of these language techniques make it hard to change a design to allow more than one instance of a class. Moreover, static member functions in C++ are never virtual, so subclasses can't override them polymorphically.

Friday, November 30, 2007

Abstract Factory Pattern

Intent
Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
Also Known As
Kit
Motivation
Consider a user interface toolkit that supports multiple look-and-feel standards, such as Motif and Presentation Manager. Different look-and-feels define different appearances and behaviors for user interface "widgets" like scroll bars, windows, and buttons. To be portable across look-and-feel standards, an application should not hard-code its widgets for a particular look and feel. Instantiating look-and-feel specific classes of widgets throughout the application makes it hard to change the look and feel later.
We can solve this problem by defining an abstract WidgetFactory class that declares an interface for creating each basic kind of widget. There's also an abstract class for each kind of widget, and concrete subclasses implement widgets for specific look-and-feel standards. WidgetFactory's interface has an operation that returns a new widget object for each abstract widget class. Clients call these operations to obtain widget instances, but clients aren't aware of the concrete classes they're using. Thus clients stay independent of the prevailing look and feel.









There is a concrete subclass of WidgetFactory for each look-and-feel standard. Each subclass implements the operations to create the appropriate widget for the look and feel. For example, the CreateScrollBar operation on the MotifWidgetFactory instantiates and returns a Motif scroll bar, while the corresponding operation on the PMWidgetFactory returns a scroll bar for Presentation Manager. Clients create widgets solely through the WidgetFactory interface and have no knowledge of the classes that implement widgets for a particular look and feel. In other words, clients only have to commit to an interface defined by an abstract class, not a particular concrete class.
A WidgetFactory also enforces dependencies between the concrete widget classes. A Motif scroll bar should be used with a Motif button and a Motif text editor, and that constraint is enforced automatically as a consequence of using a MotifWidgetFactory.
Applicability
· Use the Abstract Factory pattern when
· a system should be independent of how its products are created, composed, and represented.
· a system should be configured with one of multiple families of products.
· a family of related product objects is designed to be used together, and you need to enforce this constraint.
· you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.
Structure

Participants
· AbstractFactory (WidgetFactory)
o declares an interface for operations that create abstract product objects.
· ConcreteFactory (MotifWidgetFactory, PMWidgetFactory)
o implements the operations to create concrete product objects.
· AbstractProduct (Window, ScrollBar)
o declares an interface for a type of product object.
· ConcreteProduct (MotifWindow, MotifScrollBar)
o defines a product object to be created by the corresponding concrete factory.
o implements the AbstractProduct interface.
· Client
o uses only interfaces declared by AbstractFactory and AbstractProduct classes.
Collaborations
· Normally a single instance of a ConcreteFactory class is created at run-time. This concrete factory creates product objects having a particular implementation. To create different product objects, clients should use a different concrete factory.
· AbstractFactory defers creation of product objects to its ConcreteFactory subclass.
Consequences
The Abstract Factory pattern has the following benefits and liabilities:
1. It isolates concrete classes. The Abstract Factory pattern helps you control the classes of objects that an application creates. Because a factory encapsulates the responsibility and the process of creating product objects, it isolates clients from implementation classes. Clients manipulate instances through their abstract interfaces. Product class names are isolated in the implementation of the concrete factory; they do not appear in client code.
2. It makes exchanging product families easy. The class of a concrete factory appears only once in an application—that is, where it's instantiated. This makes it easy to change the concrete factory an application uses. It can use different product configurations simply by changing the concrete factory. Because an abstract factory creates a complete family of products, the whole product family changes at once. In our user interface example, we can switch from Motif widgets to Presentation Manager widgets simply by switching the corresponding factory objects and recreating the interface.
3. It promotes consistency among products. When product objects in a family are designed to work together, it's important that an application use objects from only one family at a time. AbstractFactory makes this easy to enforce.
4. Supporting new kinds of products is difficult. Extending abstract factories to produce new kinds of Products isn't easy. That's because the AbstractFactory interface fixes the set of products that can be created. Supporting new kinds of products requires extending the factory interface, which involves changing the AbstractFactory class and all of its subclasses. We discuss one solution to this problem in the Implementation section.
Implementation
Here are some useful techniques for implementing the Abstract Factory pattern.
1. Factories as singletons. An application typically needs only one instance of a ConcreteFactory per product family. So it's usually best implemented as a Singleton .
2. Creating the products. AbstractFactory only declares an interface for creating products. It's up to ConcreteProduct subclasses to actually create them. The most common way to do this is to define a factory method for each product. A concrete factory will specify its products by overriding the factory method for each. While this implementation is simple, it requires a new concrete factory subclass for each product family, even if the product families differ only slightly. If many product families are possible, the concrete factory can be implemented using the Prototype pattern. The concrete factory is initialized with a prototypical instance of each product in the family, and it creates a new product by cloning its prototype. The Prototype-based approach eliminates the need for a new concrete factory class for each new product family. Here's a way to implement a Prototype-based factory in Smalltalk. The concrete factory stores the prototypes to be cloned in a dictionary called partCatalog. The method make: retrieves the prototype and clones it:
make: partName
^ (partCatalog at: partName) copy
The concrete factory has a method for adding parts to the catalog.

addPart: partTemplate named: partName
partCatalog at: partName put: partTemplate
Prototypes are added to the factory by identifying them with a symbol:
aFactory addPart: aPrototype named: #ACMEWidget
A variation on the Prototype-based approach is possible in languages that treat classes as firstclass objects (Smalltalk and Objective C, for example). You can think of a class in these languages as a degenerate factory that creates only one kind of product. You can store classes inside a concrete factory that create the various concrete products in variables, much like prototypes. These classes create new instances on behalf of the concrete factory. You define a new factory by initializing an instance of a concrete factory with classes of products rather than by subclassing. This approach takes advantage of language characteristics, whereas the pure Prototype-based approach is language-independent. Like the Prototype-based factory in Smalltalk just discussed, the class-based version will have a single instance variable partCatalog, which is a dictionary whose key is the name of the part. Instead of storing prototypes to be cloned, partCatalog stores the classes of the products. The method make: now looks like this:

make: partName
^ (partCatalog at: partName) new
3. Defining extensible factories. AbstractFactory usually defines a different operation for each kind of product it can produce. The kinds of products are encoded in the operation signatures. Adding a new kind of product requires changing the AbstractFactory interface and all the classes that depend on it.
A more flexible but less safe design is to add a parameter to operations that create objects. This parameter specifies the kind of object to be created. It could be a class identifier, an integer, a string, or anything else that identifies the kind of product. In fact with this approach, AbstractFactory only needs a single "Make" operation with a parameter indicating the kind of object to create. This is the technique used in the Prototype- and the class-based abstract factories discussed earlier.
This variation is easier to use in a dynamically typed language like Smalltalk than in a statically typed language like C++. You can use it in C++ only when all objects have the same abstract base class or when the product objects can be safely coerced to the correct type by the client that requested them. The implementation section of Factory Method shows how to implement such parameterized operations in C++. But even when no coercion is needed, an inherent problem remains: All products are returned to the client with the same abstract interface as given by the return type. The client will not be able to differentiate or make safe assumptions about the class of a product. If clients need to perform subclass-specific operations, they won't be accessible through the abstract interface. Although the client could perform a downcast (e.g., with dynamic_cast in C++), that's not always feasible or safe, because the downcast can fail. This is the classic trade-off for a highly flexible and extensible interface.
Sample Code
We'll apply the Abstract Factory pattern to creating the mazes we discussed at the beginning.
Class MazeFactory can create components of mazes. It builds rooms, walls, and doors between rooms. It might be used by a program that reads plans for mazes from a file and builds the corresponding maze. Or it might be used by a program that builds mazes randomly. Programs that build mazes take a MazeFactory as an argument so that the programmer can specify the classes of rooms, walls, and doors to construct.

class MazeFactory {
public:
MazeFactory();
virtual Maze* MakeMaze() const
{ return new Maze; }
virtual Wall* MakeWall() const
{ return new Wall; }
virtual Room* MakeRoom(int n) const
{ return new Room(n); }
virtual Door* MakeDoor(Room* r1, Room* r2) const
{ return new Door(r1, r2); }
};
Recall that the member function CreateMaze builds a small maze consisting of two rooms with a door between them. CreateMaze hard-codes the class names, making it difficult to create mazes with different components. Here's a version of CreateMaze that remedies that shortcoming by taking a MazeFactory as a parameter:
Maze* MazeGame::CreateMaze (MazeFactory& factory) {
Maze* aMaze = factory.MakeMaze();
Room* r1 = factory.MakeRoom(1);
Room* r2 = factory.MakeRoom(2);
Door* aDoor = factory.MakeDoor(r1, r2);
aMaze->AddRoom(r1);
aMaze->AddRoom(r2);
r1->SetSide(North, factory.MakeWall());
r1->SetSide(East, aDoor);
r1->SetSide(South, factory.MakeWall());
r1->SetSide(West, factory.MakeWall());
r2->SetSide(North, factory.MakeWall());
r2->SetSide(East, factory.MakeWall());
r2->SetSide(South, factory.MakeWall());
r2->SetSide(West, aDoor);
return aMaze;
}

We can create EnchantedMazeFactory, a factory for enchanted mazes, by subclassing MazeFactory. EnchantedMazeFactory will override different member functions and return different subclasses of Room, Wall, etc.

class EnchantedMazeFactory : public MazeFactory {
public:
EnchantedMazeFactory();
virtual Room* MakeRoom(int n) const
{ return new EnchantedRoom(n, CastSpell()); }
virtual Door* MakeDoor(Room* r1, Room* r2) const
{ return new DoorNeedingSpell(r1, r2); }
protected:
Spell* CastSpell() const;
};

Now suppose we want to make a maze game in which a room can have a bomb set in it. If the bomb goes off, it will damage the walls (at least). We can make a subclass of Room keep track of whether the room has a bomb in it and whether the bomb has gone off. We'll also need a subclass of Wall to keep track of the damage done to the wall. We'll call these classes RoomWithABomb and BombedWall. The last class we'll define is BombedMazeFactory, a subclass of MazeFactory that ensures walls are of class BombedWall and rooms are of class RoomWithABomb. BombedMazeFactory only needs to override two functions:
Wall* BombedMazeFactory::MakeWall () const {
return new BombedWall;
}
Room* BombedMazeFactory::MakeRoom(int n) const {
return new RoomWithABomb(n);
}
To build a simple maze that can contain bombs, we simply call CreateMaze with a BombedMazeFactory.

MazeGame game;
BombedMazeFactory factory;
game.CreateMaze(factory);
CreateMaze can take an instance of EnchantedMazeFactory just as well to build enchanted mazes. Notice that the MazeFactory is just a collection of factory methods. This is the most common way to implement the Abstract Factory pattern. Also note that MazeFactory is not an abstract class; thus it acts as both the AbstractFactory and the ConcreteFactory. This is another common implementation for simple applications of the Abstract Factory pattern. Because the MazeFactory is a concrete class consisting entirely of factory methods, it's easy to make a new MazeFactory by making a subclass and overriding the operations that need to change. CreateMaze used the SetSide operation on rooms to specify their sides. If it creates rooms with a BombedMazeFactory, then the maze will be made up of RoomWithABomb objects with BombedWall sides. If RoomWithABomb had to access a subclass-specific member of BombedWall, then it would have to cast a reference to its walls from Wall* to BombedWall*. This downcasting is safe as long as the argument is in fact a BombedWall, which is guaranteed to be true if walls are built solely with a BombedMazeFactory. Dynamically typed languages such as Smalltalk don't require downcasting, of course, but they might produce run-time errors if they encounter a Wall where they expect a subclass of Wall. Using Abstract Factory to build walls helps prevent these run-time errors by ensuring that only certain kinds of walls can be created. Let's consider a Smalltalk version of MazeFactory, one with a single make operation that takes the kind of object to make as a parameter. Moreover, the concrete factory stores the classes of the products it creates.

First, we'll write an equivalent of CreateMaze in Smalltalk:
createMaze: aFactory
room1 room2 aDoor
room1 := (aFactory make: #room) number: 1.
room2 := (aFactory make: #room) number: 2.
aDoor := (aFactory make: #door) from: room1 to: room2.
room1 atSide: #north put: (aFactory make: #wall).
room1 atSide: #east put: aDoor.
room1 atSide: #south put: (aFactory make: #wall).
room1 atSide: #west put: (aFactory make: #wall).
room2 atSide: #north put: (aFactory make: #wall).
room2 atSide: #east put: (aFactory make: #wall).
room2 atSide: #south put: (aFactory make: #wall).
room2 atSide: #west put: aDoor.
^ Maze new addRoom: room1; addRoom: room2; yourself

As we discussed in the Implementation section, MazeFactory needs only a single instance variable partCatalog to provide a dictionary whose key is the class of the component. Also recall how we implemented the make: method:
make: partName
^ (partCatalog at: partName) new
Now we can create a MazeFactory and use it to implement createMaze. We'll create the factory using a method createMazeFactory of class MazeGame.
createMazeFactory
^ (MazeFactory new
addPart: Wall named: #wall;
addPart: Room named: #room;
addPart: Door named: #door;
yourself)

A BombedMazeFactory or EnchantedMazeFactory is created by associating different classes with the keys. For example, an EnchantedMazeFactory could be created like this:

createMazeFactory
^ (MazeFactory new
addPart: Wall named: #wall;
addPart: EnchantedRoom named: #room;
addPart: DoorNeedingSpell named: #door;
yourself)

That’s IT folks