Applying UML and Patterns: An Introduction to ObjectOriented Analysis and Design and Iterative Development, Third Edition [Electronic resources]

Craig Larman

نسخه متنی -صفحه : 472/ 419
نمايش فراداده

38.17. Designing a Transaction with the Command Pattern

The last section took a simplified view of transactions. This section extends the discussion, but does not cover all transaction design issues. Informally, a transaction is a unit of worka set of taskswhose tasks must all complete successfully, or none must be completed. That is, its completion is atomic.

In terms of the persistence service, the tasks of a transaction include inserting, updating, and deleting objects. One transaction could contain two inserts, one update, and three deletes, for example. To represent this, a

Transaction class is added [Ambler00b].Fowler01], the order of database tasks within a transaction can influence its success (and performance).

Fowler02].

For example:

  1. Suppose the database has a referential integrity constraint such that when a record is updated in TableA that contains a foreign key to a record in TableB, the database requires that the record in TableB already exists.

  2. Suppose a transaction contains an INSERT task to add the TableB record, and an UPDATE task to update the TableA record. If the UPDATE executes before the INSERT, a referential integrity error is raised.

Ordering the database tasks can help. Some ordering issues are schema-specific, but a general strategy is to first do inserts, then updates, and then deletes.

Mind that the order in which tasks are added to a transaction by an application may not reflect their best execution order. The tasks need to be sorted just before their execution.

This leads to another GoF pattern: Command.

Command

Context/Problem

How to handle requests or tasks that need functions such as sorting (prioritizing), queueing, delaying, logging, or undoing?

Solution

Make each task a class that implements a common interface.

This is a simple pattern with many useful applications; actions become objects, and thus can be sorted, logged, queued, and so forth. For example, in the PFW, Figure 38.15 shows Command (or task) classes for the database operations.

Figure 38.15. Commands for database operations.

BMRSS96], which can queue, log, prioritize, and execute the commands.