【发布时间】:2012-11-08 22:56:30
【问题描述】:
在下面的代码中,我想在 IHedgehog 接口中将属性 Bristles of Hedgehog 作为 IBristles 公开,因为 a) 这样我可以只公开 getter 和 b) 在外部程序集中我不必引用所有Bristle 用于更复杂方法(如 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。
有更好/常用的模式吗?
【问题讨论】: