模版方法模式

使用场景

把几个对象中相同方法放到模版对象中,目的是为了提升代码的维护性。

image

image

image

实现

/// <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);

总结

模版方法模式就是通过把不变行为搬移到超类,去除子类中的重复代码来体现它的优势。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值