How can I simplify similar method calls between a group of static objects?

I have several static β€œform” classes that I use in my program, and since each of the static classes must perform the same operations, I wonder if there is a way to generalize the method call. If the classes were not static, I would just used the interface.

Here is the gist of my situation:

public static Triangle { public int getNumVerts() { return 3; } public bool isColliding() { return Triangle Collision Code Here } } public static Square { public int getNumVerts() { return 4; } public bool isColliding() { return Square Collision Code Here } } 

What I would prefer to do is simply call Shape.getNumVerts() instead of my current switch statement:

 switch (ShapeType) { case ShapeType.Triangle: Triangle.GetNumVerts(); case ShapeType.Square: Square.GetNumVerts(); } 

I could just use polymorphism if singletones were used instead of static classes, but single numbers should be avoided, and I would need to pass a ton of links around so that I could process individual shapes as needed.

Is there a way to group these static classes, or is this switch statement as good as it is going to get?

+4
source share
1 answer

It is not clear if you need separate Triangle and Square classes. You can eliminate them and have a Shape class with methods that take a ShapeType argument. But it also comes with a switch in fact.

 public static class Shape { public static int GetNumVerts(ShapeType type) { switch (type) { case ShapeType.Triangle:return 3; case ShapeType.Square:return 4; //... } } } 

Regarding switch , I assume that this is the normal and normal use of this method.

However, you can have separate Triangle and Square classes, and you have your switch in the Shape.GetNumVerts method. It will allow you to call Shape.GetNumVerts(ShapeType.Triangle); , i.e. switch encapsulated in the Shape class and used only once there.

 public static class Shape { public static int GetNumVerts(ShapeType type) { switch (type) { case ShapeType.Triangle:return Triangle.GetNumVerts(); case ShapeType.Square:return Square.GetNumVerts(); //... } } } 
0
source

All Articles