简体   繁体   中英

How to partly initialize c++ objects when I don't need all values from the database?

I'm trying to cut down on the amount of network queries in my c++ program (to increase speed), and when displaying search results, I don't want each (of the sometimes thousands) of objects found in the search to initialize themselves completely from the database when I only need to display part of this information.

It is much faster to perform one bigger query where I get all the information I want to display about the objects at once in the query (for example, for each object/row I select the id, the name and the location), passing them to a bigger constructor, and letting all other members be default values. Previously, and in other cases where I need the complete object, I just pass the ID to the object, then call initializeFromDatabase() directly to set all the other values.

//current solution (problem is, I might need many constructors like this for different purposes)
auto *myobject = new MyObject(345, "ObjectName", "Europe");
//no further (costly) initialization since I only need the following 2 values for my search results.
myobject->getName();
myobject->getLocationName();

//prevous solution (resulting in too many queries)
auto *myobject = new MyObject(345);
myobject->initializeFromDatabase();
myobject->getName();
myobject->getLocationName();
//I could also query the other 30 or so members here, everything is set.

This doesn't feel like good practice though, I would need other custom constructors for say, another search window displaying other kinds of data about the objects.

Are there any general best practices / a suitable design pattern to solve this sort of problem? Should I create a “Search object” that is its own class and that can then be used to create the complete object when needed? Or always initialize with only the database ID (setting a flag that the object is not initialized yet) and use the setters I need?

I found that a solution to this would be to use some sort of Lazy Loading, since I want to quickly load part of the object for the list, then load all of it if a user clicks on one of the objects. For example, a Virtual Proxy or the Ghost Design pattern would be suitable. I simply create a proxy object for displaying the search results (and for other lists in the program) that can create the full object on demand. Every proxy object has one constructor so I avoid the problem of using lots of different constructors for different purposes.

See Chapter 11 of Patterns of Enterprise Application Architecture by Martin Fowler (published by Addison-Wesley Professional, 2002)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM