However, when I am hugging myself for the above modifications,
a practical problem hits me in the head. As depicted above, when the user right
clicks the items in the ListView control, we have to decide to which instance
of the sub classes to establish according to the related info of the
currently-clicked service object in the ListView control. To gain a more
intuitive understanding with this, look at the following.
Listing 9
private void startByServiceNameToolStripMenuItem_Click(object sender, EventArgs e)
{
string serviceName = lvService.SelectedItems[0].SubItems[0].Text;
string activeType= lvService.SelectedItems[0].SubItems[2].Text;
Switch (activeType)
{
Case activeType.Singleton.ToString():
ServiceManager=new SingletonServiceManager();
break;
Case activeType.SingleCall.ToString():
ServiceManager=new SingleCallServiceManager();
break;
Case activeType.Activation.ToString():
ServiceManager=new ActivationServiceManager();
break;
}
ServiceManager.StartService(serviceName);
}
You can easily discover that we have made the greatest
efforts to eliminate the use of the switch sentence for now. However, the switch
sentence, like a "phantom," again appears before us. The new design
hands over the branch sentence related trouble to the caller. That is to say, the
existing structure still bears some fatal flaw in terms of availability.
There is also a problem with the implementation of method StartAllServices.
If we invoke the method StartAllServices of SingletonServiceManager, it only
means to start the Singleton mode related service objects. Therefore, if we want
to start all service objects, we have to create all the sub objects of
ServiceManager, and then call their related StartAllServices methods. In this
way, the code of the caller will become rather complicated and cause the low performance
as well.
Listing 10
private void munStartAll_Click(object sender, EventArgs e)
{
ServiceManager m1,m2,m3;
m1=new SingletonServiceManager();
m2=new SingleCallServiceManager();
m3=new ActivationServiceManager();
m1.StartAllServices();
m2.StartAllServices();
m3.StartAllServices();
}
Obviously, the Template Method pattern efficiently improved the
reusability of code, while at the same time increased the invoking difficulty
of the caller. Such a result is not what we would like to see.