I'm trying to implement interfaces in my design but not sure if this is correct or if there is a better way to do it.
What I need to do is
open a text file
keep searching blocks of text until I find a string that matches against one of the classes that defines that string pattern
process the string I found
continue processing file where I left off
This is the code I'm using so far, but not sure if the design is correct. Maybe something about creating a new instance of each stringType class just to check if the string matches with the one defined in the class seems wrong to me. I don't need to create the instance of the object until I actually need to do work on it.
EDIT - Forgot to add the process function, not sure if that changes anything
static void Main(string[] args)
{
//get types that implement IStringType interface
List<IStringType> types = TypeFactory.GetTypeList();
//scan text file and check against the types, store any matches found
var stringMatches = from t in types
where Regex.IsMatch(sourceString, t.stringPattern)
select t.getNewInstance(Regex.Match(sourceString,t.stringPattern).Value);
if (stringMatches.Any())
{
//process string matches
}
}
public class stringType1 : IStringType
{
public string stringPattern { get { return @"(?m)^TEST1.+[\r\n]"; } set { this.stringPattern = value; } }
private string _Message { get; set; }
public stringType1() { }
public stringType1(string str)
{
_Message = str;
}
public string ProcessString(string match)
{
//specific code to processes stringType1
}
public IStringType getNewInstance(string msg)
{
return (IStringType)(new stringType1(msg));
}
}
public class stringType2 : IStringType
{
public string stringPattern { get { return @"(?m)^BLAH2.+[\r\n]"; } set { this.stringPattern = value; } }
private string _Message { get; set; }
public stringType2() { }
public stringType2(string str)
{
_Message = str;
}
public string ProcessString(string match)
{
//specific code to processes stringType2
}
public IStringType getNewInstance(string msg)
{
return (IStringType)(new stringType2(msg));
}
}
public interface IStringType
{
string stringPattern { get; set; }
string ProcessString(string str);
IStringType getNewInstance(string str);
}
public static class TypeFactory
{
public static List<IStringType> GetTypeList()
{
List<IStringType> types = new List<IStringType>();
types.AddRange(from assembly in AppDomain.CurrentDomain.GetAssemblies()
from t in assembly.GetTypes()
where t.IsClass && t.GetInterfaces().Contains(typeof(IStringType))
select Activator.CreateInstance(t) as IStringType);
return types;
}
}