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 IProcessBoth the cleaning and drying process must be develop as class instead of method. The classes must implement IProcess interface:
{
// execute the process.
void Execute();
}
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 RunAllProcessThe 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.
{
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();
}
}
}
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 : IProcessThen, add a new process:
{
public void Execute()
{
System.Console.WriteLine("polishing..");
}
}
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