L
L
Lisik2022-01-19 20:59:25
C++ / C#
Lisik, 2022-01-19 20:59:25

What is the best architectural pattern for creating geometric shapes?

I have an interface Shapethat defines several variables (Area, Perimeter) and several methods (GetArea, GetPerimeter).
After that, I create shapes by inheriting the above interface (for example: public class Square : Shapes).
But when displaying these figures (that is, information about them, such as perimeter, area, etc.), I have a question: how to do it beautifully and correctly?
I organized the output of the figures through switch:

public class Show
    {
        public static void Display(Shape shape)
        {
            string shp = shape.ToString();

            switch (shp)
            {
                case "Shapes.Square":
                    Console.WriteLine($"This figure is square. ■\nIts area is {Shape.GetArea(shape)}.\nIts perimeter is {Shape.GetPerimeter(shape)}.\n\n");
                    break;
                default:
                    break;
            }
        }
    }


But it may happen that there will be a lot of these figures, and it casewill be a mockery to prescribe one for each. This is where I thought about some architectural pattern that would help organize all this competently.

PS I looked at the patterns on the site refactoring.guru, but I didn’t decide which one is better https://refactoring.guru/en/design-patterns/catalog

Answer the question

In order to leave comments, you need to log in

2 answer(s)
@
@insighter, 2022-01-19
@Lisik

In patterns, it is necessary to build on the functionality. First you need to decide not on how to make it more beautiful or faster, but on what exactly needs to be done.
If you need to display text that depends entirely on the data that is attached to the shape, then make an interface

public interface ITalkingShape
{
string SayAboutYourself();
}

public class Square : ITalkingShape
{
  string SayAboutYourself()
  {
    return $"figure is square. ■\nIts area is {Shape.GetArea(shape)}.\nIts perimeter is {Shape.GetPerimeter(shape)}.\n\n";
  }
}

public static void Display(ITalkingShape shape)
        { 
Console.WriteLine(shape.SayAboutYourself())
}

I don't think you need any patches.

G
GavriKos, 2022-01-19
@GavriKos

Well, the most primitive - the figure should provide information about itself. Those. Shape needs a GetInfo method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question