i use simple factory pattern like this:
public class Father
{
public virtual int field1;
public virtual int Dosth()
{
}
}
public class Son:Father
{
//inherit field1 from Father
public override int Dosth();//override Father's method
public string ex_field;
public string string Ex_method()
{
}
}
public class Factory
{
public static Father CreateObj(string condition)
{
switch(condition)
{
case("F"):
return new Father();
case("S"):
return new Son();
default:
throw new exception("you have no choice");
}
}
}
in the code ,I use a real class instead of a abstract class as the factory class. because the class Son just have something expand in Father Class base(most context can use father's ).if Father and Son inherit a abstract class by each.Class son can't inherit Father's fields and methods. so my question is :anything not good will happen in future if write as fllow (i feel not good but can't find a better one )? is there a better way?
If your classes don't have that much in common use an interface and have the factory create objects that have a specific interface instead of a specific class
Create an interface with the common fields/methods and have both Father and Son implement it:
public interface IFamily
{
int field1;
int Dosth();
}
public class Father : AbstractA, IFamily
{
// Implementation goes here
int field1;
int Dosth() {
// Do magic
}
}
public class Son : AbstractB, IFamily
{
// Implementation goes here
int field1;
int Dosth() {
// Do magic
}
}
Your factory would then be:
public class Factory
{
public static IFamily CreateObj(string condition)
{
switch(condition)
{
case("F"):
return new Father();
case("S"):
return new Son();
default:
throw new exception("you have no choice");
}
}
}
This implementation is preferred to creating deep inhertance hierarchies.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.