我使用如下的简单工厂模式:
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");
}
}
}在代码中,我使用真实类而不是抽象类作为工厂类。因为Son类只是在父类基础上进行了扩展(大多数上下文都可以使用父类),所以.if父子继承了each.Class的抽象类,Son不能继承父类的字段和方法。所以我的问题是:如果像fllow那样写,将来会发生任何不好的事情(我感觉不好,但找不到更好的)?有没有更好的方法?
发布于 2012-07-13 16:23:39
如果您的类没有那么多共同之处,请使用接口,并让工厂创建具有特定接口而不是特定类的对象
创建一个带有公共字段/方法的接口,并让父亲和儿子都实现它:
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
}
}你的工厂将会是:
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");
}
}
}这种实现方式比创建深层继承层次结构更可取。
https://stackoverflow.com/questions/11444158
复制相似问题