微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 用于重构基于许多参数进行计算的类的最佳设计模式

我正在重构一组类,如下所示进行一些价格计算.
计算基于许多参数完成.
代码是:

public interface IParcel {
    int SourceCode { get; set; }
    int DestinationCode { get; set; }
    int weight{get;set;}
    decimal CalculatePrice();
}

public abstract class GeneralParcel : IParcel {
    //implementation of inteface properties
    //these properties set with in SourceCode & DestinationCode 
    //and are used in CalculatePrice() inside classes that inherit from GeneralParcel 
    protected SourceProvinceCode{get; protected set;}
    protected DestinationProvinceCode{get;protected set;}

    //private variables we need for calculations
    private static ReadOnlyDictionary<int,List<int>> _States_neighboureness;
    private static ReadOnlyCollection<City> _Citieslist;
    private static ReadOnlyCollection<Province> _Provinceslist;

    protected ReadOnlyCollection<City> Citieslist {get { return _Citieslist; }}

    protected ReadOnlyCollection<Province> ProvincesList {get { return _Provinceslist; }}

    protected ReadOnlyDictionary<int,List<int>> StatesNeighboureness {get {return _States_neighboureness; }}

    //constructor code that initializes the static variables

    //implementation is in concrete classes
    public abstract decimal CalculatePrice();
}

public Expressparcel : GeneralParcel {
    public decimal CalculatePrice() {
        //use of those three static variables in calculations
        // plus other properties & parameters
        // for calculating prices 
    }
}


public SpecialParcel : GeneralParcel {
    public decimal CalculatePrice() {
        //use of those three static variables in calculations
        // plus other properties & parameters
        // for calculating prices 
    }
}

现在,代码有效地使用“策略模式”.

我的问题是那三个静态属性,实际上不是包裹对象的一部分,它们只需要进行价格计算,所以建议使用哪种设计模式或包装(重构)?

是否有必要的另一个接口(&然后将那些静态属性包装在里面?,甚至使静态该类,因为它基本上只是一些计算),那么如何将它连接到IParcel?
这样做,如何在SpecialParcel&中实现CalculatePrice(). Expressparcel课程?

public interface IPriceCalculator {
    decimal CalculatePrice();
}

编辑:以上只是所有系统的大图,还有其他考虑,在评论中,我们讨论它们,我再次在这里写它们以清除事物.

所有ParcelTypes都有Bulkdiscount.当客户发送超过10个包裹(或任何阈值)时发生批量发布,当一个客户将超过10个包裹发送到唯一目的地(只有一个接收者)时,也会有特殊折扣.现在,在每个宗地类型的CalculatePrice()中管理此类折扣.即使是低于7公斤包裹的百叶窗也有折扣.

现在还有3个parceltype,我在这里只展示了2个.但是我们将来需要添加其他类型(TNT和dhl支持).
每种类型都有许多服务,客户可以选择并支付它.
例如,短信服务或电子邮件服务&等等.

解决方法

就个人而言,虽然其他人可能会说包裹不应该知道如何计算自己的运费,但我不同意.你的设计已经确定有三种不同类型的包裹有三种不同的计算方式,所以对于我的(幼稚的)眼睛来说,对象应该有一个方法,例如,这是完全合适的. CalculatePrice().

如果你真的想这样,那么你需要两个IParcelPriceCalculator(或者你称之为)的实现,以及GeneralParcel上的抽象工厂方法来创建具体的ExpressparcelPriceCalculator或SpecialParcelPriceCalculator类.就个人而言,我认为这有点过分,尤其是因为代码将紧密耦合到每个GeneralParcel实现.

但是,我会考虑分别制作城市和省的静态属性.这只是更整洁,如果我维护代码,那就是我期望找到它们的地方.国家邻居应该进入省,或者甚至可能为自己的阶级辩护.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐