在下面的代码中,我想在 IHedgehog 接口中将属性 Bristles of Hedgehog 作为 IBristles 公开,因为a)这样我可以只公开 getter 和 b)在外部程序集中我不必引用所有的程序集鬃毛用于更复杂的方法,如 FindBristleDNA。从直觉上看,这是正确的做法:
// straightforward interface for simple properties of Bristles --
// more complicated methods not exposed
public interface IBristles {
int Quantity{ get; }
}
public class Bristles : IBristles {
public int Quantity{ get; set; }
public MyObscureAssembly.ComplicatedObject FindBristleDNA(){ ... }
}
// simple interface for Hedgehog, which in turn exposes IBristles
public interface IHedgehog {
bool IsSquashed { get; }
IBristles Bristles { get; }
}
// Here, Hedgehog does not properly implement IHedgehog, even though
// Bristles implement IBristles. Will not compile.
public class Hedgehog : IHedgehog {
public bool IsSquashed { get; set; }
public Bristles Bristles { get; set; }
}
我的选择是直接在 IHedgehog 界面上公开 Bristle(我不想这样做),或者创建另一个名称不同的属性(我也不想这样做,我希望 IHedgehog拥有 Bristle 属性,就像 IBristles 拥有 IsSquashed 属性一样。)
public interface IHedgehog {
bool IsSquashed { get; }
IBristles ReadOnlyBristles { get; }
}
public class Bar : IBar {
public bool IsSquashed { get; set; }
public Bristles Bristles { get; set; }
public IBristles ReadOnlyBristles { get { return this.Bristles; }
}
这似乎相当不雅。
当然,在处理实际的 Hedgehog 对象时,我们需要 getter 和 setter 功能齐全,并且返回的对象是适当的 Bristle 对象。但是,IHedgehog 只需要从 Bristle getter 中返回 IBristles。
有没有更好/常用的模式?