C# – which pattern is most intuitive for a calculator app

Architecturecdesign-patterns

The title says it all. I'm trying to build a calculator application (for self-learning purposes). The application is going to have a very common UI, with plus(+), minus(-), multiply(*) and a divide(/) button. Also, the app can do, real-number as well as complex-number calculations.

So, the situation here is, depending upon the mode(normal or complex), the same button should perform different calculation ? Which pattern should I be using for this situation ? I feel, strategy pattern should be a good fit, but then, I don't exactly know how to implement that – I mean, I'm just not sure about how to design my classes, what to have as Interfaces, and what as delegates.

CURRENTLY, MY DESIGN CONTAINS


IOperation
{
  Do();
}
Add:IOperation{}
Subtract:IOperation{}
Multiply:IOperation{}
Divide:IOperation{}
Root:IOperation{} //not supported by ComplexNumber
ISupportedOperation 
{ 
   IList<IOperation> SupportedOps {get;}
}
INumber : ISupportedOperation {}
RealNumber:INumber{}
ComplexNumber : INumber {}
  1. Interface names starts with I
  2. All others are concrete classes

BUT IT'S A MESS. And, I'm totally lost within my own classes, and interfaces.

PS: Of course, I can do this using if/else, but that's not what I want to do. Not because I forcefully want to use a pattern, but because, those if-else will be scattered everywhere in the program for eg. ReadInput, PlusButtonClick, MinusButtonClick, etc. And, as I understand, design patterns are supposed to avoid these kind of situations of code-repetitions, by clever/tricky re-organization of the existing code.

PPS: Sorry for being too verbose.

Best Answer

You're doing this backwards. Forget about the design patterns for awhile.

Just build your calculator program. Build it from scratch, and just design it however it is intuitive to you. Think about it for a few minutes, come up with a few ideas, then roll with it, start to finish.

While you are trying to implement your calculator, you might not design it right the first time and will have to restructure it now and then as you learn more about what's involved in your design. This is the process of learning, and this will teach you about how you've structured your code to attack the problem at hand.

Then, after you've done that, then take a look at the design patterns described in the GoF book, and see what patterns most closely describe how you ended up designing your calculator. Now you know what those patterns are used for, and now you'll know how to choose what pattern makes sense to apply when.

Design patterns are not building blocks, they are names for common structural paradigms, to improve communication with other developers.