Consider Factory and IFactory to be part of a solution to library responsible for instaciating new classes.
Library:
interface IFactory {
object New();
}
class Factory {
public static Factory Builder() {
return new Factory();
}
private Dictionary<Type, IFactory> factories =
new Dictionary<Type, IFactory>();
...........................
...........................
//more code
....................
....................
Example of usage:
School isel = new School("ISEL");
Degree [] degrees = {
new Degree("LEIC"),
new Degree("LEIM"),
...};
Random rand = new Random();
Factory builder = Factory.Builder()
.For<School>(() => isel)
.For<Degree>(() => degrees[rand.Next(degrees.Length)]);
Student s1 = builder.New<Student>();
Console.WriteLine(s1); // Nr = 0, School = ISEL, Degree = LEIC
Person p1 = builder.New<Person>();
Console.WriteLine(p1); // Id = 0, Name = , School = ISEL
More description:
- the For(...) method adds in factories and instance of IFactory for the generator passed as a param. The generator has to return a value compatible with T. - the New() method returns an instance of T through constructors of T(chosen at randoom) and passing each param its value as default or instance of IFactory for that param type, if it exists in factories.
Note: Neither arrays or IEnumerables are considered as params
Aucun commentaire:
Enregistrer un commentaire