mercredi 14 juin 2017

C# is factory pattern right pattern when constructor needs multiple inputs?

I wanted to understand/get your view on this example: My usecase is slightly different but this example illustrates the issue.

Assume you can have different shapes: line, square, cube

Line has a property: x Square has two properties: x, y Cube has 3 properties: x, y, z

Each of these 3 c# classes calculates its Weight differently. All classes above implement Ishape interface.

You have your main class like below that calls ShapeFactory to get appropriate shape.

Public class WeightCalculator{

public void GetWeight() {

Var shape = ShapeFactory.CreateShape(x,y,z);
Return shape.CalcWeight()
} 
} 

ShapeFactory:

Looks at values of x, y, z. If y ==0 then If z ==0 return new Line(x) return new Square(x, y) ; return new Cube(x, y, z)

Now the problem I have is that i have 9 properties that can change the implementation that needs to be returned.

How best should I implement it? Is factory pattern right aporoach?

Aucun commentaire:

Enregistrer un commentaire