Re: design pattern problem
Why don't you substitute your fixed list of operators:
Code:
if ((x == '+') || (x == '-') || (x == '*') || (x == '/') || (x == '(') || (x == ')'))
with something more flexible such as an ArrayList of chars?
Or better yet, use List<char> and then use the List<T>.Contains(T t) method to see if the char is an operator.
Re: design pattern problem
or perhaps a list of your class: List<SeriesOperator> operators....
One other thing, please learn about code tags. They're easy to use and make your code readable:
Code:
class SeriesOperator
{
private static List<char> operators = new List<char>();
private int _precedence;
public abstract double eval(double lhs, double rhs);
public SeriesOperator(int precedence)
{
_precedence = precedence;
}
public static bool IsAnOperator(char x)
{
if (operators.Contains(x))
{
return true;
}
else
{
return false;
}
}
public static SeriesOperator CreateOperator(char x)
{
SeriesOperator ret = null;
switch (x)
{
case '+':
{
ret = new Add(x);
break;
}
case '-':
{
ret = new Subract(x);
break;
}
default:
break;
}
}
Re: design pattern problem
But then how would you initialize the list?
Re: design pattern problem
I would create a Builder Class, that Initialized the List. This would have to be modified (something does), but it would be a distinct file, that only contained the initialization, and therefore edits could not corrupt the abstract class.
Re: design pattern problem
you could also delegate IsOperator check to the implementation class so the base abstract class doesn't need any modification when new implementation is added, and the only list you have will be the list of implementations.
Code:
abstract class SeriesOperator
{
private int _precedence;
private static List<SeriesOperator> _registeredOperators = new List<SeriesOperator>();
public abstract double eval(double lhs, double rhs);
protected abstract bool IsOperator(char x);
public SeriesOperator(int precedence)
{
_precedence = precedence;
}
public static void RegisterOperator(SeriesOperator operatorImpl)
{
_registeredOperators.Add(operatorImpl);
}
public static bool IsAnOperator(char x)
{
bool retval = false;
foreach (SeriesOperator operatorImpl in _registeredOperators)
{
if (operatorImpl.IsOperator(x))
{
retval = true;
break;
}
}
return retval;
}
}