流畅的有序构造函数的接口

时间:2013-09-25 07:50:41

标签: c# interface constructor fluent

我为一个流畅的有序构造函数创建了一个接口,我写了这段代码:

public interface IMyObjectFactory: IObjectWithProperty
{
  int objectId { get; set; }
  IObjectWithProperty WithObjectId(int id);
}

public interface IObjectWithProperty
{
  IObjectWithProperty WithObjectId(int id);
  MyObject Create();
}

第二个接口需要在构造方法

中强制执行顺序

impl是这样的:

public class MyObjectFactory: IMyObjectFactory
{
    public int objectId { get; set; }
    private MyObjectFactory() { }
    public static IObjectWithProperty BeginCreation()
    {
        return new ObjectFactory();
    }
    public IObjectWithProperty WithObjectId(int id)
    {
        objectId = id;
        return this;
    }

    public MyObject Create()
    {
        return new MyObject(this);
    }
}

这是我的目标:

public class MyObject
{
  public int Id { get; set; }
  public MyObject(IMyObjectFactory factory)
  {
    this.Id = factory.objectId;
  }
}

所以我可以写

MyObject mo = MyObjectFactory.BeginCreation().WithObjectId(1).Create();

但:

  • 我必须在构造函数的interface和impl中定义属性,并且不太喜欢
  • 静态BeginCreation方法没有接口
  • 我必须公开impl属性,而我想要内部
  • 在界面中我收到此警告:Warning 7 'FunzIA.DL.Factory.Interfaces.IMyObjectFactory.WithObjectId(int)' hides inherited member 'FunzIA.DL.Factory.Interfaces.IObjectWithProperty.WithObjectId(int)'. Use the new keyword if hiding was intended.

但不是新方法,我需要第二个界面来强制执行命令

有什么建议吗?感谢

2 个答案:

答案 0 :(得分:3)

public class MyObjectFactory: IMyObjectFactory
{
  private int objectId;
  private MyObjectFactory() { }

  public static IObjectWithProperty BeginCreation()
  {
    return new ObjectFactory();
  }

  public IObjectWithProperty WithObjectId(int id)
  {
    objectId = id;
    return this;
  }

  public MyObject Create()
  {
    return new MyObject(objectId);
  }
}

public class MyObject
{
  public int Id { get; set; }
  public MyObject(int objectId)
  {
    this.Id = objectId;
  }
}

我的意见:

  • 您可以删除WithObjectId中的IMyObjectFactory。你通过继承获得它。此设置是您收到警告的原因。
  • BeginCreation很好。在某些时候,你必须创建真实世界的对象,这是不可能只有接口。你需要真正的课程。
  • 我永远不会让MyObject知道任何工厂。工厂知道并创造物体,而不是相反。 Create应构建MyObject。这也导致无需拥有objectId属性(无论如何你都不喜欢)。

答案 1 :(得分:0)

我是这样做的:

  • 根本不想让类构造函数可见,我只想让工厂可以访问


public interface IMyObjectFactory: IObjectWithProperty
{
  int objectId { get; set; }
}

public interface IObjectWithProperty
{
  IObjectWithProperty WithObjectId(int id);
  MyObject Create();
}

public class MyObjectFactory: IMyObjectFactory
{
  public int objectId;
  private MyObjectFactory() { }

  public static IObjectWithProperty BeginCreation()
  {
    return new MyObjectFactory();
  }

  public IObjectWithProperty WithObjectId(int id)
  {
    objectId = id;
    return this;
  }

  public MyObject Create()
  {
    return new MyObject(this);
  }
}

public class MyObject
{
  public int Id { get; set; }
  public MyObject(IMyObjectFactory factory)
  {
    this.Id = factory.objectId;
  }
}