Creating a factory with enum controlling which implementation to create
Hey guys,
I just wanted to share a factory system I built, where you use an enum to request which child class you want the factory to create.
For example:
Vehicle vehicle = this.factory.Create(Vehicle.Car);
Vehicle would now contain the child class "Car".
I couldn't find a lot of information on how to do this when googling, so I figured it could be nice for future zenject users.
Base class & Installers
using Zenject;
public class PetBaseState
{
public virtual void Start() { }
public virtual void Update() {}
public virtual void End() {}
public class Factory : Factory<PetStates, PetBaseState> {}
public class CustomFactory : IFactory<PetStates, PetBaseState>, IValidatable
{
private DiContainer container;
public CustomFactory(DiContainer container)
{
this.container = container;
}
public PetBaseState Create(PetStates petState)
{
switch(petState)
{
case PetStates.Idle:
return this.container.Instantiate<PetIdleState>();
}
return null;
}
public void Validate()
{
this.container.Instantiate<PetIdleState>();
}
}
}
Child class
using Zenject;
public class PetIdleState : PetBaseState
{
public override void Start() {}
public override void Update() {}
public override void End() {}
}
Installer
using Zenject;
public class PetInstaller : Installer<PetInstaller>
{
public override void InstallBindings()
{
this.Container.BindFactory<PetStates, PetBaseState, PetBaseState.Factory>().FromFactory<PetBaseState.CustomFactory>();
}
}
How you can create an instance
this.stateFactory.Create(PetStates.Idle)
Let me know if you guys have any improvement suggestions!
Posted Jun 30, 2017, 1:14 AM UTC · edited
This is close to something I was attempting to do this morning. I'm reading a byte sequence off a socket, and given the message code (long/int64), I was hoping to use Zenject magic to find the appropriate class to instantiate with the rest of the binary payload. This differs from your use case in that we have an implied int->type mapping, we don't have the raw type available. Since we're already doing explicit binding (either within types and/or factories), it seems like duplicate effort to specifically enumerate the different message types within a large case/switch statement.
I was hoping to use the DIContainer BindFactory, but with the 'Id' call otherwise supported, eg: Bind Generic Factory to Concrete Factory With Id of KeyBytes
At which point, during deserialization, I could resolve the appropriate ConcreteFactory subclass by specifying the KeyBytes, and feed in my payload to the constructor / Create() in a subtype-agnostic manner.
I'm having trouble mixing-and-matching the Bind and Resolve calls. This is probably complicated due to me running this code in a standalone VS project - we're going to use this code w/in multiple Unity projects, so I'd like to just export the DLL for Unity use.