【发布时间】:2020-03-03 14:21:02
【问题描述】:
开头的代码示例:
internal class ClubHouse : ILeasable
{
public int Id { get; set; }
public int AreaInSquareFeet { get; set; }
}
public class Parking : ILeasable
{
public int Id { get; set; }
public int CarCapacity { get; set; }
}
internal interface ILeasable
{
int Id { get; set; }
}
class LeasableRepository
{
private List<ILeasable> _leasable = new List<ILeasable>()
{
new ClubHouse() {Id = 208, AreaInSquareFeet = 7500 },
new ShowRoom(){ Id = 202, AreaInSquareFeet = 4000 },
new Parking() {Id = 504, CarCapacity = 4},
};
private Dictionary<int, ILeasable> _leasableDictionary = new Dictionary<int, ILeasable>();
public LeasableRepository()
{
_leasableDictionary = _leasable.ToDictionary(x => x.Id, x => x);
}
public ILeasable GetLeasable(int id)
{
if (_leasableDictionary.ContainsKey(id)) return _leasableDictionary[id];
return null;
}
}
public class ChargeCalculatingFacade
{
LeasableRepository leasableRepository = new LeasableRepository();
public void ShowLeasingCharges(int id)
{
var leasable = leasableRepository.GetLeasable(id);
var leasingCharge = GetLeasingCharges(leasable);
}
private int GetLeasingCharges(ILeasable leasable)
{
// This is not possible as I can't be sure that leasable is ClubHouse
var property = (ClubHouse) leasable;
var areaInSquareFeet = property.AreaInSquareFeet;
return areaInSquareFeet * 10;
}
}
现在,在 ChargeCalculatingFacade 类中,在方法 ShowLeasingCharges(int id) 中,基于 id,我调用了 GetLeasable(int id),它返回 ILeasable 的实现之一。但是它会作为接口 ILeasable 返回。
我将该 ILeasable 传递给私有方法 GetLeasingCharges(leasable) 以根据 AreaInSquareFeet 计算租赁费用。
现在,leasable 参数只是 ILeasable,它只有“Id”属性可用。现在如何识别作为参数传递的具体类实现,我可以将它转换为像这样得到 AreaInSquareFeet
var property = (ClubHouse) leasable;
var areaInSquareFeet = property.AreaInSquareFeet;
但上面的代码是不可行的,因为我不确定可租用的是否是 ClubHouse,因为它只是根据 ID 从字典中选择可租用的。
所有类都没有相同的附加属性。例如,Parking 具有附加属性“CarCapacity”。我有 10 个这样的类,现在不能放 10 个 if 逻辑来检查接口是否是必需的类类型。
我想知道一些设计模式或一些 SOLID 原则是否可以简化设计。
我有以下问题:
- 在这种情况下如何获取 areaInSquareFeet
- 拥有一个具有少量方法和属性的接口,并在 concreate 类中再次具有其他公共方法或属性,这是一种好习惯吗?
注意:我不想使用反射。如果没有反射是不可能的,我想改变一个设计。有什么设计建议吗?在这种情况下可以使用任何设计模式吗?'
谢谢。 三田
【问题讨论】: