3

在我的程序中,一些对象需要其他对象(依赖),我使用 Factory 作为我的创建模式。

现在,我该如何解决一个简单的依赖问题?

这是我为解决我的问题所做的一个例子。我想知道将所需的对象发送到 Create 方法是否不是什么可怕的错误。

//AbstractBackground
// - SpecialBackground
// - ImageBackground
// - NormalBackground
class Screen{
    List<AbstractBackground> list;
    Cursor cursor;
    ContentManager content;

    public void load(string[] backgroundTypes){
        //is this okay? --------------->
        AbstractBackground background = BackgroundFactory.Create(backgroundTypes[0], cursor, content);
        list.add(background);
    }
}

class BackgroundFactory{
    static public AbstractBackground Create(string type, Cursor cursor, ContentManager content){

        if( type.Equals("special") ){
            return new SpecialBackground(cursor, content);
        }

        if( type.Equals("image") ){
            return new ImageBackground(content);
        }

        if( type.Equals("normal") ){
            return new NormalBackground();
        }
    }
}
4

3 回答 3

5

它是功能性的,但是,如果添加更多类型,它可能会变得很麻烦。
根据我个人对简单工厂的偏好,实现将是:

enum BackgroundFactoryType
{
  Special,
  Image,
  Normal,
}

static class BackgroundFactory{

  static Dictionary<BackgroundFactoryType, Func<Cursor, ContentManager, AbstractBackground>> constructors;

  static BackgroundFactory()
  {
    //initialize the constructor funcs
    constructors = new Dictionary<BackgroundFactoryType, Func<Cursor, ContentManager, AbstractBackground>>();
    constructors.Add(BackgroundFactoryType.Special, (cursor, content) => new SpecialBackground(cursor, content));
    constructors.Add(BackgroundFactoryType.Image, (_, content) => new ImageBackground(content));
    constructors.Add(BackgroundFactoryType.Normal, (_, __) => new NormalBackground());
  }

  static public AbstractBackground Create(BackgroundFactoryType type, Cursor cursor, ContentManager content)
  {
    if (!constructors.ContainsKey(type))
      throw new ArgumentException("the type is bogus");

    return constructors[type](cursor, content);
  }
}

或者你可以简单地做:

static class BackgroundFactory{

  static public AbstractBackground Create(BackgroundFactoryType type, Cursor cursor, ContentManager content)
  {
    switch (type)
    {
      case BackgroundFactoryType.Special:
        return new SpecialBackground(cursor, content);
      case BackgroundFactoryType.Image:
        return new ImageBackground(content);
      case BackgroundFactoryType.Normal:
        return new NormalBackground();
      default:
        throw new ArgumentException("the type is bogus");
    }
  }
}

这种方法的一个很好的副作用是只需要一点点工作就可以使这个东西配置驱动而不是硬编码。

于 2012-12-31T09:05:58.387 回答
4

简单的回答,看起来不错。如果您抽象地考虑这一点,您就是通过 create 方法将对象注入到构造函数中。这种技术没有问题,我推荐。

稍后,如果您需要更改实现,您可以根据需要创建其他创建方法,而不会破坏任何内容。

于 2012-12-31T08:50:43.103 回答
1

您的代码中没有什么比这更难看的了,除了如果您的依赖树增长,您创建的工厂方法将变得复杂。为了分解具有各种和明确的依赖关系的类型,您可能最好选择IoC基于工厂。通过在容器中注册依赖项,您将拥有具有所需依赖项的自动注入构造函数。

于 2012-12-31T08:54:03.320 回答