将接口属性暴露为接口的模式

时间:2012-11-08 22:56:30

标签: design-patterns interface

在下面的代码中,我想在IHedgehog界面中将属性Bristles of Hedgehog暴露为IBristles,因为a)这样我可以在外部程序集中公开getter和b)我不必引用所有Bristles用于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界面上暴露Bristles(我不想这样做),要么创建另一个具有不同名称的属性(我真的不想这样做,我会像IHedgehog那样拥有属性Bristles,就像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完全正常工作,并且返回的对象是一个合适的Bristles对象。但是,IHedgehog只需要从猪鬃吸气剂中返回IBristles。

是否有更好/常用的模式?

2 个答案:

答案 0 :(得分:2)

使用显式接口实现:

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; } }
}

答案 1 :(得分:0)

public class Hedgehog : IHedgehog 
{
    private Bristles _bristles;

    public bool IsSquashed { get; set; }

    public IBristles Bristles 
    { 
       get {return _bristles;}
       set {_bristles = value;}
    }
}
我应该这么想。要实现IHedgehog,你需要一个返回IBristles的getter,而不是Bristles