M G Vinod Kumar\’s Technology Blog

April 24, 2006

Marker Pattern aka Marker Interface Pattern

Filed under: .NET, Pattern — mgvinod @ 10:22 am

The Marker Pattern is popularly known as Marker Interface Pattern. I removed the Interface since this pattern can be implemented in two ways. Let us consider each of the ways.

1. Using an interface

First an interface is created as given below.

interface ITransactionAware{

}

Then, the class implements the interface.

 

class ClassWithMarkerInterface : ITransactionAware{

}

Using reflection, class can be checked to whether it implements the interface or not. Based on that result, any required action can be taken.

 

ClassWithMarkerInterface clsInterface = new ClassWithMarkerInterface();

if (clsInterface is ITransactionAware){

//start transaction

}

 

2. Using an attribute

Instead of an interface, an attribute is used.

class TransactionAttribute : System.Attribute{

}

The class is then marked with the above attribute.

 

[Transaction]

class ClassWithAttributeMarker {

}

The code to check for attribute is little more verbose than using the interface.

 

ClassWithAttributeMarker clsAttribute = new ClassWithAttributeMarker();

if (clsAttribute.GetType().IsDefined(typeof(TransactionAttribute),false)){

//start transaction

}

 

As you can see, using an attribute is slower than the normal interface. Purists would argue that an attribute should be used, but if performance is your top criteria then interfaces are the way.

 

 

 

Dispose pattern in depth

Filed under: .NET, Design Guidelines, Pattern — mgvinod @ 9:41 am

Dsipose pattern is one of the most often used and mentioned patterns within .NET world. If you are interested in knowing the details, you should read this from the source.

Blog at WordPress.com.