gpt4 book ai didi

java - 在这种情况下,组合模式是一个好的选择吗?

转载 作者:行者123 更新时间:2023-12-01 21:09:13 25 4
gpt4 key购买 nike

这是我遇到的一个设计困境......

在我的程序中,我有不同类型的条目 - 数字、文本、日期、图像等。

我的第一个想法是使用继承来构建模型,如下所示:

Entry 
-- NumericEntry (extends Entry)
-- TextualEntry (extends Entry)
-- DateEntry (extends Entry)
-- ImageEntry (extends Entry)

然后我可以有一个 Entry 对象列表,每个对象都知道如何通过公共(public)成员(即 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他们讨论了类似的问题。

关于java - 在这种情况下,组合模式是一个好的选择吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41505446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com