I am new to design patterns and working my way through the Factory Method and Strategy patterns. I understand that Factory is a creational pattern and Strategy is behavioral but I struggle to understand when to use which one. For example, I have the following classes that updates client details based on the company specified:
public interface IUpdateDetails { void UpdateDetails(); }
public class UPSUpdateDetails : IUpdateDetails
{
public void UpdateDetails() => Console.WriteLine("Call web service to update details for UPS...");
}
public class FedExUpdateDetails : IUpdateDetails
{
public void UpdateDetails() => Console.WriteLine("Update database for FedEx...");
}
public class DHLUpdateDetails : IUpdateDetails
{
public void UpdateDetails() => Console.WriteLine("Send Email for DHL...");
}
I can create a Factory to return the correct class:
public class UpdateDetailsFactory
{
public static IUpdateDetails Create(string type)
{
switch (type)
{
case "UPS":
return new UPSUpdateDetails();
case "DHL":
return new DHLUpdateDetails();
case "FedEx":
return new FedExUpdateDetails();
default:
throw new ArgumentException();
}
}
}
and implement it as follows:
// Using Factory
string company = "UPS"; // Get company from database
IUpdateDetails updateDetails = UpdateDetailsFactory.Create(company);
updateDetails.UpdateDetails();
Console.ReadLine();
or I can use the Strategy pattern:
public class UpdateDetailsContext
{
private IUpdateDetails strategy;
public void SetStrategy(IUpdateDetails updateDetails) => strategy = updateDetails;
public void Update() => strategy.UpdateDetails();
}
and implement it as follows:
// Using Strategy
UpdateDetailsContext context = new UpdateDetailsContext();
context.SetStrategy(UpdateDetailsFactory.Create(company));
context.Update();
Console.ReadLine();
My question is - am I understanding the patterns correctly? What is the difference between using the one over the other?