I'm creating a functional Factory where I define what kind of output it is and what the required implementation methods are.
With this implementation, when I try to use the object obj
within the function that does every factory process of that object, it can not interpret it as being Bar type.
The idea is that I can have the same statement
FooFactory.build()
for multiple types, changing only the encapsulated implementation and always having aFoo
as the return.
How to solve?
My code looks like this:
public abstract class Factory<T> where T : class {
public abstract T Build<U>(U obj) where U : class;
}
public class Quadrado {
public int Largura { get; set; }
public int Altura { get; set;}
}
public class Retangulo {
public int Largura { get; set; }
public int Altura { get; set; }
}
public class QuadradoFactory: Factory<Quadrado> {
public override Quadrado Build<Retangulo>(Retangulo o) =>
new Quadrado() { Largura = o.Largura, Altura = o.Largura };
}
public class Program {
public static void Main() {
var f = new QuadradoFactory();
var r = new Retangulo(){ Largura=2, Altura=4 };
var q = f.Build<Retangulo>(r);
System.Console.WriteLine(
"Largura: " + q.Largura +
"Altura: " + q.Altura
);
}
}