Strategy Pattern
Summary: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
Sample Code
Code
public abstract class ShootingStrategy
{
public abstract void TakePhoto();
}
public class LandscapeStrategy : ShootingStrategy
{
public override void TakePhoto()
{
Console.WriteLine("Taking photo with low ISO and great focal distance.");
}
}
public class SportsStrategy : ShootingStrategy
{
public override void TakePhoto()
{
Console.WriteLine("Taking photo with high ISO and fast shutter speed.");
}
}
public class ShootingMethod
{
private ShootingStrategy _shootingStrategy;
public void SetShootingStrategy(ShootingStrategy shootingStrategy)
{
this._shootingStrategy = shootingStrategy;
}
public void Shoot()
{
_shootingStrategy.TakePhoto();
}
}
Usage
var shootingMethod = new ShootingMethod();
System.Console.WriteLine("\nSeaside photo with the camera on a tripod:");
shootingMethod.SetShootingStrategy(new LandscapeStrategy());
shootingMethod.Shoot();
System.Console.WriteLine("\nCyclism photo handholding the camera:");
shootingMethod.SetShootingStrategy(new SportsStrategy());
shootingMethod.Shoot();
Output
Seaside photo with the camera on a tripod:
Taking photo with low ISO and great focal distance.
Cyclism photo handholding the camera:
Taking photo with high ISO and fast shutter speed.
Comments
Post a Comment