20 Factories

WHAT’S IN THIS CHAPTER?

  • How factories separate use from construction
  • Applying factory methods to aggregates
  • Using a factory method for reconstruction
  • Knowing when to use a factory

Wrox.com Code Downloads for This Chapter

The wrox.com code downloads for this chapter are found at www.wrox.com/go/domaindrivendesign on the Download Code tab. The code is in the Chapter 20 download and individually named according to the names throughout the chapter.

How do you create, persist, and retrieve domain objects while maintaining a domain model that is not distracted by technical concerns? The life cycle of complex domain objects may need coordination to begin and when being persisted. Ensuring invariants are met on creation is achieved through the utilization of the Gang of Four factory pattern.

The Role of a Factory

Aggregates, entities, and value objects can become complex when you’re creating a domain model for large and rich domains. If intimate knowledge is required to ensure valid instances of a dependent object are created, it can cloud the expressiveness of the domain. The knowledge of other objects’ invariants breaks the Single Responsibility Principle (SRP). It is recommended that you separate use from construction and explicitly encapsulate creation logic within a factory object if it is complex or if it can be expressed better. Object creation is not a domain concern, but it does live within the domain layer of an application. You will rarely talk about factories ...

Get Patterns, Principles, and Practices of Domain-Driven Design now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.