vendredi 13 mars 2015

Factory pattern for creating sub classes derived from interface with generic type

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) -



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 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.


Aucun commentaire:

Enregistrer un commentaire