开发者

how to implement a common behavior for regexp singletons in C#?

开发者 https://www.devze.com 2023-02-04 18:52 出处:网络
I want t开发者_StackOverflow中文版o write a singleton to test regular expressions, every singleton has to have its own expression (a singleton for mail, a singleton for identificacion numbers etc.).

I want t开发者_StackOverflow中文版o write a singleton to test regular expressions, every singleton has to have its own expression (a singleton for mail, a singleton for identificacion numbers etc.).

I think it should be done using an protected or public abstract static field... something like:

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
}

Practically, the specialized class should only know how to tests its associated regexp.

Thanks,


This sounds like it should simply be a static class:

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

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

If it makes sense, you can group such classes in a single interface:

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


What about:

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;
            }
        }
    }

And usage:

emailTester.Instance.test("some text");
0

精彩评论

暂无评论...
验证码 换一张
取 消