【问题标题】:Pattern for Exposing Interface Property as Interface将接口属性暴露为接口的模式
【发布时间】: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。

有更好/常用的模式吗?

【问题讨论】:

    标签: design-patterns interface


    【解决方案1】:

    使用显式接口实现:

    public class Hedgehog : IHedgehog 
    {
        public bool IsSquashed { get; set; }
    
        // your public property
        public Bristles Bristles { get; set; }
    
        // implements the interface
        IBristles IHedgehog.Bristles { get { return Bristles; } }
    }
    

    【讨论】:

    • 谢谢,这正是我想要的。
    【解决方案2】:
    public class Hedgehog : IHedgehog 
    {
        private Bristles _bristles;
    
        public bool IsSquashed { get; set; }
    
        public IBristles Bristles 
        { 
           get {return _bristles;}
           set {_bristles = value;}
        }
    }
    

    我应该想想。要实现 IHedgehog,您需要一个返回 IBristles 而不是 Bristle 的 getter

    【讨论】:

    • 谢谢,但是这种模式的问题在于,如果您不想与“真正的”刺猬互动,那么您就不会暴露出完整的鬃毛对象。但是,即使 Bristle 实现了 IBristles,IHedgehog 也必须暴露 Bristle 或一些其他间接属性。
    • 是的,但是使用接口的重点不是直接公开实现。一旦您放置了一套鬃毛类型的设置器,IBristle 的所有好处,就直接进入垃圾箱。以上是老实说的黑客攻击。
    猜你喜欢
    • 2019-12-14
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 2015-10-30
    • 2010-10-13
    • 1970-01-01
    相关资源
    最近更新 更多