gpt4 book ai didi

java - 如何正确管理对数据库对象的访问?

转载 作者:行者123 更新时间:2023-12-02 19:20:50 25 4
gpt4 key购买 nike

我想知道是否有更好的解决方案来解决我的问题。更好的是,并非 Segment 类的每个对象都必须创建新的数据库对象。

我试图在我的程序中只保留一个数据库,因为该数据库非常大,而且我确信有一种更有效的解决方案。

数据库将 SegmentInformation 类的对象保存在列表中。每个对象都包含每个 Segment 对象实例化所需的许多信息。

图层类包含段列表。 Layers 构造函数包含一个带有 ID 的数组。每个段都将从数据库获取其信息,具体取决于它调用数据库的 ID。

Database {
List<SegmentInformation> segInfoList;

public SegmentInformation getSegInfos( int id ){
return segInfoList.get(id);
}
}

Layer{
List<Segments> segmentList;

public Layer( int[] segmentIDs ){
for (int i : segmentIDs){
segmentList.add( new Segment( segmentIDs[i] ) );
}
}
}

Segment{
double value1;
//....
double valuenN;

public Segment(int sID){
Database db = new Database();
SegmentInformation info = db.getSegInfos( sID );
value1 = info.getValue1();
//....
valueN = info.getValueN();
}
}

我试图避免使用包含数据库的全局静态变量。对于实例化所有 Segment 对象的更合适的方法有什么建议吗?

最佳答案

使用 Singleton 来包含所有 Segment 对象:

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one "single" instance. This is useful when exactly one object is needed to coordinate actions across the system. The term comes from the mathematical concept of a singleton.

https://en.wikipedia.org/wiki/Singleton_pattern

关于java - 如何正确管理对数据库对象的访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58630523/

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