Hello i have to create a complex object , and i wanted to use the factory pattern for it.However i do not know what to do with the additional dependencies that the object needs in order to be created.
Dependencies
public class SomeService
{
}
public class SomeOtherService
{
}
Hierarchy
public abstract class NeededObjectBase
{
public readonly int Type {get;set;} //id selected by the factory
public abstract void DoSomething();
}
public class A:NeededObjectBase
{
private SomeService service;
A(SomeService service){ this.service=service;}
public override void DoSomething(){}
}
public class B:NeededObjectBase
{
public B(SomeService service,SomeOtherService otherService){
this.service=service;
this.otherService=otherService
}
public SomeOtherService service;
public SomeOtherService otherService;
public override void DoSomething(){}
}
Factory
public class Factory
{
public static NeededObjectBase CreateInstance(int type)
{
switch(type)
{
case 0:return new A(); //this would need SomeService => new A(someService)
case 1:return new B(); // this would need SomeService & SomeOtherService => new B(someService,someOtherService);
default: return new A();
}
}
}
Usage
public class Aggregate
{
private SomeService s1;
private SomeOtherService s2;
public void UseNeededObject(int type)
{
NeededObjectBase neededObject=Factory.CreateInstance(type);
neededObject.DoSomething();
}
}
If you look in the code things happen like this:
I have an Aggregate
class where i keep my dependencies.
Inside its method i use the Factory
based on the type
parameter in order to create the right object.
However i do not know what to do with the dependencies.Should the factory get all the required dependencies in order to create the objects ?
So basically i do not know who should keep the dependencies for object creation.The factory makes the selection but how does it provide the right dependencies in order to instantiate the selection ?
P.S I would need somehow to first make the selection based on the parameter and retrieve something
from the factory and then that something to get its dependencies in order to create the final object.
Aucun commentaire:
Enregistrer un commentaire