Would like to know if the factory pattern I've implemented for my stat library is the correct way to go. I have an interface IPlayerStatsManager where the type parameter is an interface as well (IPlayerStatsModel). The IPlayerStatsManager is an interface that lists the common operations that can be performed on any class that implements IPlayerStatsModel. I've only completed the implementation for basketball and it seems to work correctly but would like to know if the way I currently have it is the most efficient way. Here's the code (some of the implementation removed for brevity)
Context
public interface IPlayerStatsModel
{
string type {get; set;}
}
// concrete implementation
public class BasketballPlayerStats : IPlayerStatsModel
{
// various class members with getters and setters
}
public interface IPlayerStatsManager<T> where T : IPlayerStatsModel
{
Task<T> GetPlayerGameStats(....);
Task<List<T>> GetPlayersGameStats(...);
// insert and update methods
}
//concrete implementation
public class BasketballPlayerStatsManager : IPlayerStatsManager<BasketballPlayerStats>
{
public BasketballPlayerStatsManager(DbContext context)
{
}
public async Task<BasketballPlayerStats> GetPlayerGameStats(...)
{
}
}
Factory
//Factory class
public class PlayerStatsFactory<IPlayerStatsManager>
{
public static IPlayerStatsManager Create(DbContext context, int sportType)
{
if (sportType == (int)Utils.SportType.Basketball)
{
return (IPlayerStatsManager)Activator.CreateInstance(typeof(BasketballPlayerStatsManager));
}
return default(IPlayerStatsManager);
}
}
I feel like there might be a better way but I'm not sure what that would look like. Any pointers would be greatly appreciated.
if
withswitch/case
orDictionary<SportType, Type>
(I'd go with the later). Also have generic Manager (looks like a Repository) for anyT
. \$\endgroup\$Activator.CreateInstance<T>() where T : new()
inside just callsnew T()
so not a big difference. No difference at all, actually :) \$\endgroup\$