2

标题可能无法很好地描述我的问题,如果有人可以将其编辑为更合适的内容,我会很高兴。无论如何:

我得到了一个组件,它应该返回产品价格,因为它的id. 它实现了一个像这样的接口:

interface IProductPriceFetcher
{
    double GetPrice(int id);
}

现在,可以从3 个不同的来源获取价格:

  • 网络服务
  • 直接来自网站源代码(报废)
  • 作为最终后备(webservice 和网站都无法访问),返回本地数据库的最新价格

为了解决这个 3-different-sources 问题,我实现了这样的类:

class MainFetcher : IProductPriceFetcher
{
    public double GetPrice(int id)
    {
        var priceFetcher = this.factory.GetWebServiceFetcher()
                        ?? this.factory.GetWebsiteFetcher()
                        ?? this.factory.GetLocalDatabaseFetcher();
        return priceFetcher.GetPrice(id);
    }
}

当然,工厂的每个方法都会返回IProductPriceFetcher,附带说明前两个可以失败并返回null;我假设GetLocalDatabaseFetcher将始终返回有意义的对象。

我的“一般疑惑……精神”

在成功的网络服务/网站调用后,我希望将获取的价格插入本地数据库,作为未来的后备案例。现在我的问题是:上面的哪部分代码应该对此负责?它应该是返回价格的具体网络获取器之一吗?或者“聚合器”获取器(MainFetcher),因为它也知道价格的来源是什么?我应该提出一些事件吗?用数据库调用注入另一个接口?将设计更改为更好?

为什么它甚至对我来说是个问题?好吧,我试图保持代码干净(不用担心,这只是我业余时间的宠物项目 - 正是为了解决这样的问题)可能考虑到 SRP/SoC。现在我似乎在从这种心态转变时遇到了问题——我的意思是,获取网页的东西怎么可能也在进行数据库插入?哦,来吧!:)

4

2 回答 2

2

如果你想要一个超级解耦的设计,我会实现一个像下面这样的Decorator类,并用它来包装 WebServiceFetcher 和 WebsiteFetcher:

class DatabaseCachingFetcherDecorator : IProductPriceFetcher
{
    private readonly IProductPriceFetcher innerFetcher;

    public DatabaseCachingFetcherDecorator(IProductPriceFetcher fetcher)
    {
        this.innerFetcher = fetcher;
    }

    public double GetPrice(int id)
    {
        double price = this.innerFetcher.GetPrice(id);

        if (price != 0) // or some other value representing "price not found"
        {
            SavePriceToDatabase(id, price);
        }

        return price;
    }

    private SavePriceToDatabase(int id, double price)
    {
        // TODO: Implement...
    }
}

然后您的工厂将实现以下方法:

public IProductPriceFetcher GetWebServiceFetcher()
{
    return new DatabaseCachingFetcherDecorator(new WebServiceFetcher());
}

public IProductPriceFetcher GetWebsiteFetcher()
{
    return new DatabaseCachingFetcherDecorator(new WebsiteFetcher());
}

这种设计将您的实际提取器与您的缓存机制分离。

编辑:我用这个答案稍微误读了你的设计,因为我假设如果无法获取价格,GetPrice 方法将返回某种 NULL 值,而不是工厂返回 NULL 值。我认为返回 NULL 的工厂有点味道,因为工厂的职责是可靠地返回对象。我会考虑更改您的GetPrice方法接口以返回一个double?可能,以允许“未找到价格”。

于 2011-05-16T16:45:20.767 回答
1

在我看来,如果你需要一个“缓存”。缓存通常作为一种方面或依赖项来实现,您可以将其注入到您的Fetcher实现中。下面我假设IPriceCache使用某种IDictionary接口,但您当然可以插入您需要的任何抽象。我还建议抽象出价格获取者的数据源......:

class MainFetcher : IPriceFetcher {

 IEnumerable< IPriceSource > mSource;
 IPriceCache mCache;

 public MainFetcher( IEnumerable< IPriceSource > pSource, IPriceCache pCache )
 {
     mSource = pSource;
     mCache = pCache; 
 }

 public double GetPrice(int pID)
 {
     double tPrice;
     // get from cache
     if (mCache.TryGet(pID, out tPrice) {
         return tPrice;
     } else {
         // throws if no source found
         tPrice = mSource
             .First(tArg => tArg != null)
             .GetPrice(pID);
         // add to cache
         mCache.Add(pID, tPrice);
     }
 }
}
于 2011-05-16T17:18:15.157 回答