- Design Patterns and Best Practices in Java
- Kamalmeet Singh Adrian Ianculescu LUCIAN PAUL TORJE
- 329字
- 2021-06-25 20:52:32
The factory pattern
As discussed in the previous chapter, inheritance is one of the fundamental concepts in object-oriented programming. Along with subtyping polymorphism, it gives us the is/a relationship. A Car object can be handled as a Vehicle object. A Truck object can be handled as a Vehicle object too. On one hand, this kind of abstraction makes our code thinner, because the same piece of code can handle operations for both Car and Truck objects. On the other hand, it gives us the option to extend our code to new types of Vehicle objects by simply adding new classes such as Bike and Van without modifying it.
When we deal with such scenarios, one of the trickiest parts is the creation of objects. In object-oriented programming, each object is instantiated using the constructor of the specific class, as shown in the following code:
Vehicle vehicle = new Car();
This piece of code implies a dependency between the class which instantiates an object and the class of the instantiated object. Such dependencies make our code tightly coupled and harder to extend without modifying it. For example, if we need to replace Car with another type, let's say Truck, we need to change the code accordingly:
Vehicle vehicle = new Truck();
But there are two problems here. First of all, our class should be open for extension but closed for modification (the open/closed principle). Second of all, each class should have only one reason to change (the single responsibility principle). Changing the main code each time we add a new class will break the open/closed principle, and having the main class responsible for instantiating vehicle objects in addition to its functionality will break the single responsibility principle.
In this case, we need to come up with a better design for our code. We can add a new class that is responsible for instantiating vehicle objects. We are going to call the pattern based on this SimpleFactory class.
- Web程序設(shè)計及應(yīng)用
- Getting Started with Citrix XenApp? 7.6
- Mastering Adobe Captivate 2017(Fourth Edition)
- Computer Vision for the Web
- Arduino開發(fā)實戰(zhàn)指南:LabVIEW卷
- Network Automation Cookbook
- Oracle 12c中文版數(shù)據(jù)庫管理、應(yīng)用與開發(fā)實踐教程 (清華電腦學(xué)堂)
- 跟老齊學(xué)Python:輕松入門
- 老“碼”識途
- Linux命令行與shell腳本編程大全(第4版)
- Tableau 10 Bootcamp
- 區(qū)塊鏈技術(shù)進階與實戰(zhàn)(第2版)
- 微信小程序開發(fā)實戰(zhàn):設(shè)計·運營·變現(xiàn)(圖解案例版)
- Backbone.js Testing
- Scratch從入門到精通