我想写一个单例来测试正则表达式,每个单例都必须有自己的表达式(一个用于邮件的单例,一个用于标识号的单例等)。
我认为应该使用受保护的或公共的抽象静态字段来完成......类似于:
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
}
实际上,专业类应该只知道如何测试其相关的正则表达式。
谢谢,
答案 0 :(得分:2)
这听起来应该只是一个静态类:
public static class EmailTester
{
static readonly Regex _regex=new Regex(...);
public static bool Test(string value)
{
return _regex.IsMatch(value);
}
}
如果有意义,您可以在单个界面中对这些类进行分组:
namespace Testers
{
public static class Emailtester
{
...
}
}
答案 1 :(得分:1)
怎么样:
public class RegExpTester
{
private readonly Regex engine;
protected RegExpTester( string expression )
if ( string.IsNullOrEmpty( expression ) )
{
throw new ArgumentException( "expression null or empty" );
}
engine = new Regex( expression );
}
public bool test( string strToBeTested )
{
return engine.IsMatch( strToBeTested );
}
}
public sealed class emailTester : RegExpTester
{
static emailTester instance = new emailTester();
emailTester() : base( "some mail expression" ) { }
public static emailTester Instance
{
get
{
return instance;
}
}
}
用法:
emailTester.Instance.test("some text");