c# - 如何在 C# 中实现正则表达式单例的常见行为?

标签 c# .net design-patterns architecture singleton

我想编写一个单例来测试正则表达式,每个单例都必须有自己的表达式(用于邮件的单例,用于识别号码的单例等)。

我认为应该使用 protected 或公共(public)抽象静态字段来完成......类似:

public abstract class RegExpTester{
    protected abstract RegExpTester tester;
    private Regex engine;

    public bool test(string strToBeTested){
        //Creates a new instance of regExpTester and test the string;
        //If instance does exist, only test. 

    }
}

public sealed class emailTester : RegExpTester {
    // Some code that I've not written since I do not
    // know where should the singleton be instantiated
}

实际上,专用类应该只知道如何测试其关联的正则表达式。

谢谢

最佳答案

这听起来应该只是一个静态类:

public static class EmailTester
{
  static readonly Regex _regex=new Regex(...);

  public static bool Test(string value)
  {
    return _regex.IsMatch(value);
  }
}

如果有意义的话,您可以将这些类分组在一个接口(interface)中:

namespace Testers
{
  public static class Emailtester
  {
  ...
  }
}

关于c# - 如何在 C# 中实现正则表达式单例的常见行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4682207/

相关文章:

c# - OData 和自定义 WCF WebGet 方法

c++ - 访客 : adding more types via inheritance

scala - 在 Scala 中使用 Cake 模式和函数之间的区别 - 为什么 Cake 模式有用?

c# - VB.NET 匿名委托(delegate)的等效 C# 代码是什么?

c# - 动态选择器 Linq To Entities

c# - 检索 Windows 体验评级

c# - 使用 MailKit (C#) 转发电子邮件

c# - 从 .NET Core 运行 PowerShell

.net - 使用域凭据连接的 SSH.NET

ios - Objective-C 和类集群模式