TransWikia.com

How to implement DAO design pattern?

Software Engineering Asked on October 29, 2021

I’m trying to learn how to implement a DAO design pattern (for a game, but this does not really matter). In my program, I have a database layer which has user objects. Then in the code, I have a DAO class DAO_USER which reads and writes to the database.

Once it reads from the database, it creates class instances of the user objects MDL_USER which model the properties of the database object such as id and name.

Then the business logic of the game will called GET and SET methods of the MDL_USER class instance.

My idea here is that, the business logic will only interact with the MDL_USER object, which that only interacts with the DAO_USER object which only interacts with the database.

The thing to note here is now I have the data in the database and a local copy of it in the MDL_USER object. If I do a SET update, I need to update the local copy and the database, but only if the database update succeeded. If I do a GET, it can just read from the local copy.

Where I am getting stuck is, in my program in the DAO_USER class, it imports the MDL_USER class just to make the class instances of it. However the MDL_USER class needs to import the DAO_USER class to call its method to update the database.

This creates a circular loop in imports and makes it error out. How can I improve this design so it works?

One Answer

in my program in the DAO_USER class, it imports the MDL_USER class just to make the class instances of it

A simple approach to solve this is by introducing a "data transfer object" DTO_USER which is created by DAO_USER and passed into MDL_USER for construction. The DTO will only contain the data, no business methods or database related methods. MDL_USER may have a constructor which takes a DTO_USER object and constructs a new instance. In the place of your code where MDL_USER objects are required, outside of DAO_USER and MDL_USER, DAO_USER is used to construct DTO_USER, and the MDL_USER constructor will be called with that object.

That way, DAO_USER and MDL_USER depend both on DTO_USER, which depends on nothing else, but neither DAO_USER depends on MDL_USER nor MDL_USER on DAO_USER.

Answered by Doc Brown on October 29, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP