简体   繁体   English

工厂模式-带有可选参数

[英]Factory Pattern - with optional parameters

I have a factory: 我有一家工厂:

  public static class AdapterFactory
  {

    public static IAdapter GetAdapter(AdapterType claimType, int mid, int tid, int siteId, string version)
    {
    }
}

My problem is that sometimes the mid, tid, siteId and version parameters are not needed to construct an "Adapter", they are specific to only some kinds of adapters. 我的问题是,有时不需要mid,tid,siteId和version参数来构建“适配器”,它们仅特定于某些类型的适配器。

What is the best approach when parameters are not always required like in this situation? 在这种情况下并非总是需要参数的最佳方法是什么?

Thanks for your help. 谢谢你的帮助。

Specalise and make more factories, for example: 专门制造更多工厂,例如:

public static class MidAdapterFactory
{
    public static IAdapter GetAdapter(AdapterType claimType, int mid)
    {
    }
}

public static class TidAdapterFactory
{
    public static IAdapter GetAdapter(AdapterType claimType, int tid)
    {
    }
}

Also consider the builder pattern. 还考虑构建器模式。

Look at optional arguments . 查看可选参数 You can give parameters default values, then omit them if you don't need them 您可以给参数提供默认值,然后在不需要时将其忽略

public static class AdapterFactory
{
    public static IAdapter GetAdapter(AdapterType claimType, 
                                      int mid = 0, 
                                      int tid = 0, 
                                      int siteID = 0, 
                                      string version = null)
    {
        // Create adapter here
    }
}

Can now be used as so: 现在可以这样使用:

var adapter1 = AdapterFactory.GetAdapter(AdapterType.Regular, 1000, 50, 10, "1.0.0.0");
var adapter2 = AdapterFactory.GetAdapter(AdapterType.Minimal);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM