Thursday, September 23, 2010

Plug and play design

Problem: we need a design that allows adding new sub-processes easily in the future. It is something like add-on or plug and play concept.

Solution: this problem can be easily resolve in C# by using interface and implement it into various classes.

For example, we need a process that is responsible for cleaning and then drying. In order to achieve the add-on concept, first, we need to define an interface:
public interface IProcess
{
// execute the process.
void Execute();
}
Both the cleaning and drying process must be develop as class instead of method. The classes must implement IProcess interface:
   public class Cleaning : IProcess
{
public void Execute()
{
System.Console.WriteLine("cleaning..");
}
}

public class Drying : IProcess
{
public void Execute()
{
System.Console.WriteLine("drying..");
}
}

Finally, we need to create a class that executes the cleaning and drying process:
   public class RunAllProcess
{
public void Run()
{
// iniatialize the list to store the Type
List< Type> list = new List< Type>();

list.Add(typeof(Cleaning));
list.Add(typeof(Drying));
// you may add more classes here in
// the future with ease...

IProcess process;

foreach (Type item in list)
{
// instantiate the object at runtime.
process = (IProcess)Activator.CreateInstance(item);

// execute the process:
process.Execute();
}
}
}
The reason of using Type list instead of IProcess list is that the object instance will not be created upon adding. It will be instantiate before you execute the process. This is to avoid executing the codes in the class's constructor (if any) which may occupy the memory.

After a while, the user might want to add a new process call polishing. This can be done easily.

Declare a new class:
   public class Polishing : IProcess
{
public void Execute()
{
System.Console.WriteLine("polishing..");
}
}
Then, add a new process:
   public class RunAllProcess
{
public void Run()
{
...
list.Add(typeof(Cleaning));
list.Add(typeof(Drying));
list.Add(typeof(Polishing)); //<==== add the new process here.
...
}
}

No comments:

Post a Comment