课程: Programming Foundations: Design Patterns
今天就学习课程吧!
今天就开通帐号,24,100 门业界名师课程任您挑!
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…
随堂练习,边学边练
下载课堂讲义。学练结合,紧跟进度,轻松巩固知识。