Unit of work is A Martin Fowlers design (architectural) pattern, to handle transactional changes in the code.
This is the quote from his book:
Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.
Martin fowler
Unit of work collects all changes about domain objects, that need to be synced (with the database) and lets committing those at the end of a (business) transaction. Tracking and syncing objects (shared state) is crucial feature. Syncing can be done more frequently, at any change, but it may have negative impact on a performance. Another reason using this pattern, is making changes atomic(all or nothing).
I found this pattern not only solving concurrency problems. I think, it also solves the state synchronization problem between two "objects". In examples below, these two modules are database and client. Unit of work synchronizes runtime objects loaded and created in the database. This pattern allows collecting changes and committing those in one atomic operation. It allows having consistent state between two modules in the system.
Though alone this pattern does not complies totally with the ACID database transaction, but it allows having A and C from the ACID.
There is no strict schema, how to use the instance of "Unit of Work" (UoW later).
- You may have a separate class to register changes and then get changes on a commit method.
- You may have a reference to a repository, which is able to commit all the changes.
- In case you are using the "Domain model" pattern, then domain object knows how to make changes in the database.
Patterns of Enterprise Application Architecture: Martin Fowler, with Dave Rice, Matthew Foemmel, Edward Hieatt, Robert Mee, and Randy Stafford
Note: The content in this article is a summary/interpretation inspired by them. Proper attribution is given to the respective authors.