1

我正在为流利的有序构造函数创建一个接口,我编写了以下代码:

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

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

第二个接口需要在构造方法中强制执行顺序

暗示是这样的:

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();

但:

  • 我必须在构造函数的接口和 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.

但不是一种新方法,我需要第二个接口来强制执行订单

有什么建议吗?谢谢

4

2 回答 2

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

我的意见:

  • 您可以WithObjectIdIMyObjectFactory. 你通过继承得到它。此设置是您收到警告的原因。
  • BeginCreation它在哪里很好。在某些时候,您必须创建真实世界的对象,而仅使用接口是不可能的。你需要真正的课程。
  • 我永远不会让MyObject任何工厂知道。工厂知道并创建对象,而不是相反。Create应该构造MyObject. 这也导致不需要拥有该objectId属性(无论如何您都不喜欢)。
于 2013-09-25T08:09:40.950 回答
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;
  }
}
于 2013-10-15T09:01:40.087 回答