From the course: Programming Foundations: Design Patterns

Unlock the full course today

Join today to access over 22,400 courses taught by industry experts or purchase this course individually.

The need for factory patterns

The need for factory patterns

From the course: Programming Foundations: Design Patterns

Start my 1-month free trial

The need for factory patterns

- We've talked about programming to interfaces, not implementations. When we program to an implementation, we get locked into concrete types, and more importantly, our code will require changes if our set of concrete types ever gets extended. It might seem interesting that by using the new operator, we're forcing ourselves into a concrete implementation. Like here where we assign duck to a new mallard duck. We'd like to use an interface like duck as the type for the variable, but ultimately, we have to create a concrete type, like mallard duck, to create a duck object. 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…

Contents