类似的函数重构模式

本文关键字:重构 模式 函数 | 更新日期: 2023-09-27 18:36:15

我有大约 20 个模式几乎相同的函数,我在站点数组上运行,使用 Site 对象创建 SiteOperation 并执行一些操作(在这种情况下使用一个参数,但有时没有或多个)

int wantedBandwidthInLBps = 2048 / 8;
foreach (Sites site in _sitesManagement.GetAll())
{
 SiteOperation siteOperation = new SiteOperation(site);
 siteOperation.LimitBandwidth(wantedBandwidthInLBps);
}
foreach (Sites site in _sitesManagement.GetAll())
{
 SiteOperation siteOperation = new SiteOperation(site);
 siteOperation.KillJames();
}
foreach (Sites site in _sitesManagement.GetAll())
{
 SiteOperation siteOperation = new SiteOperation(site);
 siteOperation.FlyToMoon(2012, new TaskIdentifier(10,20));
}

是否可以包装此代码,所以我将只发送操作,让我们说_sitesManagement哪个将在所有站点上运行此操作?

类似的函数重构模式

试试这个:

void PerformOperationOnAllSites(Action<SiteOperation> doIt) {
    foreach (Sites site in _sitesManagement.GetAll()) {
        SiteOperation siteOperation = new SiteOperation(site);
        doIt(siteOperation);
    }
}
...
_sitesManagement.PerformOperationOnAllSites(op => op.LimitBandwidth(wantedBandwidthInLBps));
_sitesManagement.PerformOperationOnAllSites(op => op.KillJames());
_sitesManagement.PerformOperationOnAllSites(op => op.FlyToMoon(2012, new TaskIdentifier(10,20));
public void DoSiteOperationActions(Action<SiteOperation> toDo)
{
        foreach (Sites site in _sitesManagement.GetAll())
        {
           SiteOperation mySiteOperation = new SiteOperation(site);
           toDo(mySiteOperation);
        }
}

然后你可以这样称呼它...

DoSiteOperationActions(so => so.FlyToMoon(2012, new TaskIdentifier(10,20)));

语法可能有点不对劲,我这里没有IDE,但更多信息在这里http://msdn.microsoft.com/en-us/library/018hxwa8.aspx

听起来像是模板方法模式的一个很好的候选者。

http://en.wikipedia.org/wiki/Template_method_pattern

    private static void InvokeMethod(Action<SiteOperation> action)
    {
        foreach (SiteOperation siteOperation in _sitesManagement.GetAll()
                               .Select(site=>new SiteOperation(site))
        {
            action(siteOperation);
        }
    }
..
    public static void KillJames()
    {
        InvokeMethod(so => so.KillJames());
    }
    public static void LimitBandwidth(int wantedBandwidthInLBps)
    {
        InvokeMethod(so => so.LimitBandwidth(wantedBandwidthInLBps));
    }
    public static void FlyToMoon(int year=2012, TaskIdentifier ti=new TaskIdentifier(10,20))
    {
        InvokeMethod(so => so.FlyToMoon(year, ti));
    }