这是我遇到的一个设计难题...
在我的程序中,我有不同类型的条目-数字,文本,日期,图像等。
我的第一个想法是使模型具有如下继承结构:
Entry
-- NumericEntry (extends Entry)
-- TextualEntry (extends Entry)
-- DateEntry (extends Entry)
-- ImageEntry (extends Entry)
然后,我可以有一个Entry对象的列表,每个对象将知道如何通过普通成员(即showData(),makeSummary()等)处理和公开其数据。如果要添加新的Entry对象,则只需添加具有该特定类型的另一个类。
但是,Java的限制以及android orm库的限制使这一过程变得非常复杂。
因此,我已经转向复合模式,但是我不确定是否正确。
所以,现在我有了这个(伪代码):
class Entry
{
Type type;
(nullable)NumericEntry numericEntry;
(nullable)TextualEntry textualEntry;
(nullable)DateEntry dateEntry;
(nullable)ImageEntry imageEntry;
public showData()
{
swicth (type)
{
case numeric: ..
case textual: ..
case date: ..
case image: ..
}
}
}
但这对我来说似乎太有线了,不是吗?
在所描述的场景中什么是正确的方法?
最佳答案
我认为您要尝试做的是合法的,但我认为此处的混合模式有些偏离。据我所知,复合模式用于分层结构(如目录结构)。
您的模型看起来很不错,使用(抽象的)基类,并从其他类型扩展它,但是我无法理解为什么要在基Entry类中拥有所有不同类型的条目。
如果我正确理解您想要的内容,那么这将更加合乎逻辑。
接口示例:
public interface Entry{
// Define all your methods as abstract and define them here
void showData();
}
public class TextualEntry implements Entry{
void showData(){
// Your implementation for textual entries here
}
}
// Repeat this for the other types of entries
您还可以考虑使用抽象类实现,该实现可以定义所有扩展类中使用的属性/字段。此外,您可以在抽象类中实现对所有扩展类具有相同实现的方法。
抽象类的例子:
abstract class Entry{
// Define your properties here that are used in all the other classes
// Define all your methods as abstract and define them here
public abstract void showData();
}
class TextualEntry extends Entry{
// Define new properties here
public override void showData(){
// Your implementation for textual entries here
}
}
// Repeat this for the other types of entries
他们在http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html上讨论了类似的问题。