Strategy pattern
Defined
Defines a family of algorithms, encapsulates each one, and makes them interchangeable.The Strategy Pattern lets the algorithm vary independently from clients that use it,
Use when client of inherited base class may have varying behaviors and dependent of scenario you may want to use one or the other interchangeably.
Identify the aspects of your application that vary and separate them from what stays the same.
Take what varies and "encapsulate" it so it wont affect the rest of your code.
Diagrams
Code Example
i.e a CARs Exhaust Noise varys dependent of what type of Car your driving
interface IExhaustNoiseBehavior()
{
private string noise;
public string Noise()
}
class SportsCarExhaustNoiseBehavior : IExhaustNoise
{
private string noise = "brrrrm"
public string Noise
{
return noise;
}
}
public class Car
{
IExhaustNoiseBehavior exhaustNoiseBehavior
public performExhaustNoise() { return ExhaustNoiseBehavior.Noise };
}
public class Ferrari : Car
{
IExhaustNoise ExhaustNoise
public Ferrari ( IExhaustNoise exhaustNoiseBehavior)
{
ExhaustNoise = new SportsCarExhaustNoiseBehavior();
}
}
No comments:
Post a Comment