abstract class Robot
{
private string _Name;
private string _NeedSomething;
private string _Command;
public Robot(string name, string needsomething)
{
_Name = name;
_NeedSomething = needsomething;
}
private void NamingName()
{
Console.WriteLine("The Robot's name is " + _Name);
}
private void PerpareSomething()
{
Console.WriteLine("Perparing " + _NeedSomething + " now.");
}
protected abstract string AppointCommand();
private void ExecuteCommand()
{
Console.WriteLine(_Command + " is Executing.");
}
private void EndCommand()
{
Console.WriteLine(_Command + " is end.");
}
public void ExecuteRobot()
{
NamingName();
PerpareSomething();
_Command = AppointCommand();
ExecuteCommand();
EndCommand();
}
}
模板
class AutoCollectInformationRobot : Robot
{
private string _Command;
public AutoCollectInformationRobot(string name, string something, string command)
: base(name, something)
{
_Command = command;
}
protected override string AppointCommand()
{
return _Command;
}
}
由模板生成的对象A
abstract class BombRobot
{
private string _Name;
private string _NeedSomething;
private string _Command;
public BombRobot(string name, string needsomething)
{
_Name = name;
_NeedSomething = needsomething;
}
private void NamingName()
{
Console.WriteLine("The Robot's name is " + _Name);
}
private void PerpareSomething()
{
Console.WriteLine("Perparing " + _NeedSomething + " now.");
}
protected abstract string AppointCommand();
private void ExecuteCommand()
{
Console.WriteLine(_Command + " is Executing.");
}
private void EndCommand()
{
Console.WriteLine(_Command + " is end.");
}
protected virtual bool BombOrNot()
{
return true;
}
public void ExecuteBomb()
{
NamingName();
PerpareSomething();
_Command = AppointCommand();
if (BombOrNot())
ExecuteCommand();
EndCommand();
}
}
由模板生成的对象B
class MailBombRobot : BombRobot
{
private string _Command;
public MailBombRobot(string name, string needsomething, string command)
: base(name, needsomething)
{
_Command = command;
}
protected override string AppointCommand()
{
return _Command;
}
protected override bool BombOrNot()
{
return false;
}
}
由模板生成的对象C
namespace TemplatePattern
{
class Program
{
static void Main(string[] args)
{
//Robot webRobot = new AutoCollectInformationRobot("WebInfomationCollecter", "Destination WEB Station", "Collect Information");
//webRobot.ExecuteRobot();
//Console.ReadKey();
BombRobot mbb = new MailBombRobot("MailBombRobot", "Be Bombed EMail Account", "Send A Mail Bomb");
mbb.ExecuteBomb();
Console.ReadKey();
}
}
}
调用者