I created a small abstract domain to illustrate the problem I encountered, so there is one.
There is a medieval game in which players are generals of their army, and the whole battle mainly depends on the battle plan, which is created before the start of the battle, in standby mode, for example, in preparation mode.
To achieve the necessary, I created an interface IBattleUnitand saved everything quite simply:
public interface IBattleUnit
{
void Move();
void Attack();
string Salute();
}
Now three types of units will do the job, therefore Archer.cs, Pikeman.csand Swordsman.csimplement the interface in much the same way:
public class Swordsman : IBattleUnit
{
private Swordsman() {}
public void Move()
{
//swordsman moves
}
public void Attack()
{
//swordsman attacks
}
public string Salute()
{
return "Swordsman at your service, master.";
}
}
private, , Barracks, factory
public static class Barracks<T> where T : class, IBattleUnit
{
private static readonly Func<T> UnitTemplate = Expression.Lambda<Func<T>>(
Expression.New(typeof(T)), null).Compile();
public static T Recruit()
{
return UnitTemplate();
}
}
. - ( ) , , , .
, , , BattlePlan , :
public static class BattlePlan
{
private static List<Type> _battleUnitTypes;
private static List<Type> _otherInterfaceImplementors;
//...
private static Dictionary<string, string> _battlePlanPreferences;
private static Type _preferedBattleUnit;
private static Type _preferedTransportationUnit;
//...
static BattlePlan()
{
//read the battle plan from file (or whereever the plan init data originate from)
//explore assemblies for interface implementors of all kinds
//and finally fill in all fields
_preferedBattleUnit = typeof (Archer);
}
public static Type PreferedBattleUnit
{
get
{
return _preferedBattleUnit;
}
}
//... and so on
}
, , - , , ...
: , , .
, :
IBattleUnit unit = Barracks<Pikeman>.Recruit();
- , , , ,
AssemblyQualifiedName, Type ( Archer, BattlePlan), , , , :
Type preferedType = BattlePlan.PreferedBattleUnit;
, , BattlePlan Type , Type Barracks, - Unit, VisualStudio2012 (resharper ) , , :
Type t = Type.GetType(BattlePlan.PreferedBattleUnit.AssemblyQualifiedName);
IBattleUnit u = Barracks<t>.Recruit();
, , , t typeof(t), IRepository... , ( ) :
Error 1 Cannot implicitly convert type 't' to 'BattleUnits.cs.IBattleUnit' Program.cs
Error 2 The type or namespace name 't' could not be found (are you missing a using directive or an assembly reference?) Program.cs
, :
, , , .
№1: : IBattleUnit , ( , ). , , , GroundUnitBase FlyingUnitBase , ... Barracks.
- BattleUnits - , , ... , , , UnitBase , - . , , .