使用场景
把几个对象中相同方法放到模版对象中,目的是为了提升代码的维护性。
实现
/// <summary>
/// 日志文件信息
/// </summary>
class LogFile { }
/// <summary>
/// 云服务日志上传接口。
/// </summary>
interface ICloudService
{
void SaveLogFile(LogFile logFile);
}
/// <summary>
/// 云服务器service模板
/// 模板方法模式
/// </summary>
abstract class CloudService : ICloudService
{
/// <summary>
/// 保存方法(通用方案)
/// </summary>
public void SaveLogFile(LogFile logFile)
{
//1、建立远程连接
Connection();
//2、序列化
Serialize();
//3、传输
Transport();
//4、回调
Callback();
}
protected abstract void Connection();
protected virtual void Serialize()
{
Console.WriteLine("日志文件序列化");
}
protected virtual void Transport()
{
Console.WriteLine("日志文件上传");
}
protected virtual void Callback()
{
Console.WriteLine("日志文件成功回调");
}
}
/// <summary>
/// 阿里云服务
/// </summary>
class AliCloudService : CloudService
{
protected override void Connection()
{
Console.WriteLine("建立阿里云连接");
}
}
/// <summary>
/// 微软云服务
/// </summary>
class AzureCloudService : CloudService
{
protected override void Connection()
{
Console.WriteLine("建立Azure云连接");
}
}
以上代码,日志序列化、上传个、回调方法都是相同的操作,建立链接每个服务的实现不同,所以让各自去实现。形成了云服务器 service 统一模板。
下面客户端调用就实现了任意切换。
LogFile logFile = new LogFile();
ICloudService cloudService = new AliCloudService();
cloudService = new AzureCloudService();
cloudService.SaveLogFile(logFile);
如果具体的服务多了的话,客户端切换也不方便,为了更好实现,我们可以引入工厂模式。
class CloudServiceFactory
{
public static ICloudService GetCloudService(string cloudServerType)
{
if (cloudServerType == null)
{
return null;
}
if (cloudServerType.Equals("ali"))
{
return new AliCloudService();
}
else if (cloudServerType.Equals("azure"))
{
return new AzureCloudService();
}
return null;
}
}
//选择云服务器 - 工厂模式
LogFile logFile = new LogFile();
ICloudService cloudService = CloudServiceFactory.GetCloudService("azure");
cloudService.SaveLogFile(logFile);
总结
模版方法模式就是通过把不变行为搬移到超类,去除子类中的重复代码来体现它的优势。