【发布时间】:2013-01-21 08:36:28
【问题描述】:
我必须根据客户类型创建对象系列。 我有一个基本抽象类 ApplicationRulesFactory,它定义 虚拟接口。很多具体的客户类都继承自这个类。
问题在于,对于某些客户说 CustomerB,我们不使用对象 Rule2 和 Rule3,因为应用程序中使用这些对象 Rule2 和 Rule3 的功能在该客户的应用程序用户界面中被禁用,所以我们没有真的需要实例化这些对象。
简化的代码在这里,即实际上 ApplicationRulesFactory 有更多的虚拟方法,以及从它继承的更具体的客户类:
class ApplicationRulesFactory
{
virtual Rule1* GetRule1() = 0;
virtual Rule2* GetRule2() = 0;
virtual Rule3* GetRule3() = 0;
.....
};
class ACustomerRulesFactory : public ApplicationRulesFactory
{
Rule1* GetRule1()
{
return new ACustomerRule1();
}
Rule2 * GetRule2()
{
return new ACustomerRule2();
}
Rule3* GetRule3()
{
return new ACustomerRule3();
}
};
class BCustomerRulesFactory : public ApplicationRulesFactory
{
Rule1* GetRule1()
{
return new BCustomerRule1();
}
Rule2* GetRule2() // not needed
{
// what to return here ?
}
Rule3* GetRule3() // not needed
{
// what to return here ?
}
};
那么我应该如何去实现这个:
1) 在基类 ApplicationRulesFactory 中返回一些默认实现:
class ApplicationRulesFactory
{
virtual Rule1* GetRule1() = 0;
virtual Rule2* GetRule2() { return new Rule2DefaultImpl();}
virtual Rule3* GetRule3() { return new Rule3DefaultIml();}
};
但这似乎是错误的,从 Rule1、Rule2 继承新类(Rule1DefaultImpl,Rule2DefaultImpl),并可能使它们具有空实现,只是为了像 ApplicationRulesFactory 中的默认实现一样返回它们
2) 或在具体类中返回默认实现并将这些方法保留在基类中纯虚拟
class BCustomerRulesFactory : public ApplicationRulesFactory
{
Rule1* GetRule1()
{
return new BCustomerRule1();
}
Rule2* GetRule2()
{
return new Rule2DefaultImpl();
}
Rule3* GetRule3()
{
return new Rule3DefaultImpl();
}
};
这些解决方案似乎也很难重新定义每个具体客户类中的方法,尽管它们不是必需的。
3) 另外我有一种感觉,也许我不应该像这样使用继承,因为这违反了继承的 IS-A 规则,导致大量方法不适用于所有具体的客户类,但是不要在没有继承的情况下如何去实现它。
任何想法
【问题讨论】:
-
它们是指针,你不能只返回NULL吗?设计方面,客户 A 和 B 是不同类型的客户,因此可能应该有 2 个子类,一个有 1 个规则,另一个有 3 个。
-
是的,我可以,但仍然怀疑这是正确的做法。
标签: c++ design-patterns abstract-class