extension pattern in .NET - Decorate the class with attributes

 Consider a simple class hierarchy with an abstract base class and 3 derived classes. A typical implementation of a factory would be a static method on the base class, like this



Problem: The above pattern is bad in different ways

       1. Base classes must have references to the sub classes and that makes it tightly coupled.

       2. Following the Open-Closed principle  (open for extension and closed for modification), we do not want to open the code for changes when in future a new class is introduced that derive from the base class.


I am using the http://en.wikipedia.org/wiki/Factory_pattern

The factory method pattern is an object-oriented creational design pattern to implement the concept of factories and deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The essence of this pattern is to "Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses."[1]  

Solutions: to make our pattern loosly coupled and Open-Closed, I prototyped a quick example in .Net using reflection. 

we want some like this.


Prototype: I created the following classes

    1. ExtensionClassFactory.cs ----> Implements the Factory

   2. ConnectionAttribute.cs     ------> Processes the Attributes that decorate the classes.

   3. Interface with 2 derived classes  (IConnection.cs is the interface, Connection1.cs, Connection2.cs are the derived classes)


Here if you see we are just passing an input to the IConnection interface. Based on the input the corresponding derived class is instantiated.

                  RESULT ---- "Hi! I am in Connection1" is read from Connection1.cs


How is it done: Implement the following classes.


1. INTERFACE CLASS - that defined the method implemented by derived classes

2. Sample Connection1.cs class that implements derived class1


3. Sample Connection2.cs classs that implements the derived class 2.



 4. EXTENSIONFACOTRY - is implemented using REFLECTION to read the attribute that decorates the CLASSES (DERIVED CLASSES

  The factory will be given the base class and the attribute value, it will looking for the derived classes and or this attribute type value combination.