I m using C# Switch case how i can replace using inheritance. case is like 1,2,3,4 so how i can implement it.
for eg:
public Blocks(int code)
{
bool[,] shp1;
switch (code)
{
case 1:
this._Width = 4;
this._Height = 1;
this._Top = 0;
this._Left = 4;
shp1 = new bool[_Width, _Height];
shp1[0, 0] = true;
shp1[1, 0] = true;
shp1[2, 0] = true;
shp1[3, 0] = true;
this.Shape = shp1;
break;
case 2:
this._Width = 2;
this._Height = 2;
this._Top = 0;
this._Left = 4;
shp1 = new bool[_Width, _Height];
shp1[0, 0] = true;
shp1[0, 1] = true;
shp1[1, 0] = true;
shp1[1, 1] = true;
this.Shape = shp1;
break;
default:
throw new ArgumentException("Invalid Block Code");
}
}
The basic idea is that instead of having a method that decides what to do based on state, you have different types of objects that have different implementations of the same method that do the right thing for that type of object.
Let's say that you now have a Car class and the values (1, 2, 3, ...) refer to various brake configurations. In your current Brake() method you have code that looks like:
public class Car
{
public void Brake()
{
switch (this.BrakeType)
{
case 1: // antilock brakes
....
case 2: // 4-wheel disc brakes, no antilock
....
case 3: // rear-drum, front-disc brakes
....
}
}
}
What you really would like to to do is have different classes that implement the Brake method. In this case, I'd have a BrakeStrategy for each of the brake types. Assign the car object the correct BrakeStrategy for it's configuration, then simply call the strategy method from the Brake method.
public class Car
{
public BrakeStrategy BrakeStrategy { get; set; }
public void Brake()
{
this.BrakeStrategy.Brake();
}
}
public class ABSBrakes : BrakeStrategy
{
public void Brake()
{
... do antilock braking...
}
}
var car = new Car { BrakeStrategy = new ABSBrakes(), ... };
car.Brake(); // does ABS braking
You can apply a Strategy pattern.
But, you must make sure that you're not trying to kill a fly with a gun, if you see what I mean.
Make sure that you do not introduce more complexity then you're trying to remove.
In some cases, replacing your switch statement with a strategy is a good solution, in other cases, it is not.
As I see your code now, I think I would opt for some kind of factory pattern ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With