非静态类工厂方法- c#

  • 本文关键字:方法 工厂 静态类 c#
  • 更新时间 :
  • 英文 :


我把这个放在一起解析出一个字符串,然后在SQL存储过程中返回3个值(我有另一个c#方法,根据您选择的输出格式格式化3个值,但是该代码没有问题,所以我没有发布它)。当我的老板看到我的代码时,他说:

"你如何拥有一个非静态类工厂方法?"你需要创建一个对象来解析一个字符串来创建一个对象来使用?

为什么把解析移到类中而不是留在原来的地方然后返回新类来保存数据?"

我已经创建了一个新类,但是我可以很容易地将它移动到另一个类中。问题是我不知道他是非静态工厂方法的意思,我也不知道如何分配值,分数和方向,而不像我那样创建TwpRng的新实例: TwpRng结果=新的TwpRng();

这是我第一次尝试c#。

public class TwpRng
{
public string Value;
public string Fraction;
public string Direction;

public TwpRng GetValues(string input)
{
    TwpRng result = new TwpRng();
    result.Value = "";
    result.Fraction = "";
    result.Direction = "";
    Regex pattern_1 = new Regex(@"(?i)^s*(?<val>d{1,3})(?<frac>[01235AU])(?<dir>[NEWS])s*$");    // Example:  0255N
    Match match_1 = pattern_1.Match(input);
    Regex pattern_2 = new Regex(@"(?i)^s*(?<val>d{1,3})(?<dir>[NEWS])s*$");    // Example:  25N
    Match match_2 = pattern_1.Match(input);
    Regex pattern_3 = new Regex(@"(?i)^s*(?<val>d{1,3})(?<frac>[01235AU])s*$");    // Example:  25A
    Match match_3 = pattern_1.Match(input);
    if (match_1.Success)
    {
        result.Value = match_1.Groups["val"].Value;
        result.Fraction = match_1.Groups["frac"].Value;
        result.Direction = match_1.Groups["dir"].Value.ToUpper();             
    }
    else if (match_2.Success)
    {
        result.Value = match_2.Groups["val"].Value;
        result.Direction = match_2.Groups["dir"].Value.ToUpper();
    }
    else if (match_3.Success)
    {
        result.Value = match_3.Groups["val"].Value;
        result.Fraction = match_1.Groups["frac"].Value;
    }
    else
    {
        result = null;
    }
    return result;
}

}

你如何有一个非静态类工厂方法?您需要创建一个对象来解析字符串以创建要使用的对象吗?

他的意思是,目前为了解析输入,你需要这样做:

var twpRng = new TwpRng(); // Doesn't really make sense to instantiate an empty object
twpRng = twpRng.GetValues(input); // just to create another one.

如果您将工厂方法GetValues设置为static:

public static TwpRng GetValues(string input)

你可以更容易地解析:

var twpRng = TwpRng.GetValues(input);

如果您更改:

public TwpRng GetValues(string input)

:

public static TwpRng GetValues(string input)

您已经从非静态模式更改为静态工厂模式。这两个函数的调用顺序如下:

TwpRng myRng = new TwpRng();
TwpRng createdRng = myRng.GetValues(input);

相对于:

TwpRng createdRng = TwpRng.GetValues(input);

其余的代码可以是相同的

扩大解释

你老板问的是静态修饰语的使用。静态方法可以在不首先实例化类(创建类的实例)的情况下调用,并且通常用于解析数据并返回类的完整实例。静态方法也可以用于实用程序类和方法(在这种情况下,实例化对象可能会过度使用),并且您只是想将一堆功能分组。

最新更新