In my program, some objects need other objects (dependency), and I’m using Factory as my creational pattern.
Now, how do I solve a simple dependency problem?
This is an example of what I’m doing to solve my problem. I want to know if sending the needed objects to the Create method is not something horribly wrong.
//AbstractBackground
// - SpecialBackground
// - ImageBackground
// - NormalBackground
class Screen{
List<AbstractBackground> list;
Cursor cursor;
ContentManager content;
public void load(string[] backgroundTypes){
//is this okay? --------------->
AbstractBackground background = BackgroundFactory.Create(backgroundTypes[0], cursor, content);
list.add(background);
}
}
class BackgroundFactory{
static public AbstractBackground Create(string type, Cursor cursor, ContentManager content){
if( type.Equals("special") ){
return new SpecialBackground(cursor, content);
}
if( type.Equals("image") ){
return new ImageBackground(content);
}
if( type.Equals("normal") ){
return new NormalBackground();
}
}
}
Simple answer, it looks good. If you think of this abstractly, you are injecting the objects into the constructor through the create method. Nothing wrong with this technique, and is something that I recommend.
Later, if you need to change the implementation, you can create other create methods as needed without breaking anything.