开发者

Visual Basic External Class Calculator

I was assigned to create a calculator that can calculate the sum, product, difference, and quotient using开发者_Python百科 an external class.

Unfortunately my teacher isn't exactly the best and I'm new to VB, I know how to create a calculator in VB.net, but when it comes to external classes, I honestly really don't know what he's talking about.

Can someone please clarify what he's asking for?


I think you will have to create classes for different operations, a very simple example is given below:

    public class Sum
{
  private int num1;
  private int num2;

  public Sum(int x, int y)
  {
    num1 = x;
    num2 = y;
  }
  public int Calculate()
  {
        return num1 + num2;
  }
}

And then use this class from Calculator class to perform summation (create new instance of this class and call calculate method).


It is difficult to guess without clearer instructions, but since that seems to come from above, I would guess that (s)he expects something resembling the command pattern.

Essentially instad of having a Calculator class with doAdd(int, int), doSubtract(int, int) etc, you could accept a Command (maybe an enum with the different operations named), and pass the calculation off to something implementing a common interface.

interface CalcCommand
{
    double calc(double a, double b);
}

Then your Calculator.AcceptCommand() function (or whatever you call it), could create and call objects that implement this interface and call them all in the same way. The real purpose of this pattern is to separate different bits of code to make them easier to maintain separately without constantly having to change the Calculator class itself.

This is a very simple example, but I hope it offers a suitable starting point. You may also wish to look up the strategy pattern, which is similar in purpose and implementation.


I agree with ADas. You could also use Shared methods in the class so that you wouldn't have to instantiate an instance in order to use them:

Public Class Operations

    Public Shared Function Sum(x As Integer, y As Integer) As Integer
        Return x + y
    End Function

    Public Shared Function Difference(x As Integer, y As Integer) As Integer
        Return x - y
    End Function

End Class

You could then call this class like this:

Dim result As Integer = Operations.Sum(5, 5)

And if the requirement for an "external class" means in a separate file, then add a new Class Library project to your solution and put the classes there. Then reference that class library from your calculator app so you can use it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜