From the course: Design Patterns: Creational

Factories

From the course: Design Patterns: Creational

Start my 1-month free trial

Factories

- [Instructor] Before we talk about factories, in general, let's talk about a concrete implementation you'll likely see often. When we use the new operator in our code to create new objects, we are forcing ourselves into a concrete implementation, like we are here with the mallard duck. We can use an interface like duck as the type of the variable to program to the interface, but ultimately, we have to create a concrete type like mallard duck to create a duck object somewhere in our code. Quite often, we end up writing code like this. Here we have a duck variable, and we use conditional logic to pick the concrete type of the duck. For instance, if we're at a picnic, we create a mallard duck, and if we're hunting, then we create a decoy duck, and if this is a bathtub, we create a rubber duck. With this code, we're making runtime decisions about which class to instantiate. When we see code like this, we know that if requirements change, and we want to add new duck types, we're going to have to open up this code and change it, and that violates the open closed principle. We might also end up writing this same code in several places in this application, making the situation even worse, so what do we do? As usual, let's look at what varies and encapsulate it.

Contents