- Mastering TypeScript 3
- Nathan Rozentals
- 236字
- 2021-07-02 12:42:56
The Factory class
Let's now move on to the Factory class itself. This class has a single, well-defined responsibility: given a date of birth, figure out whether it is less than two years ago, less than 18 years ago, or more than 18 years ago. Based on these decisions, return an instance of either an Infant, Child, or Adult class, as follows:
class PersonFactory { getPerson(dateOfBirth: Date) : IPerson { let dateNow = new Date(); // defaults to now. let currentMonth = dateNow.getMonth() + 1; let currentDate = dateNow.getDate(); let dateTwoYearsAgo = new Date( dateNow.getFullYear() - 2, currentMonth, currentDate); let date18YearsAgo = new Date( dateNow.getFullYear() - 18, currentMonth, currentDate); if (dateOfBirth >= dateTwoYearsAgo) { return new Infant(dateOfBirth); } if (dateOfBirth >= date18YearsAgo) { return new Child(dateOfBirth); } return new Adult(dateOfBirth); } }
The PersonFactory class has only one function, getPerson, which returns an object of type IPerson. The function creates a variable named dateNow, which is set to the current date. We then find the current month and date from the dateNow variable. Note that the JavaScript function, getMonth, returns 0 - 11, and not 1 - 12, so we correct this by adding 1. This dateNow variable is then used to calculate two more variables, dateTwoYearsAgo and date18YearsAgo. The decision logic then takes over, comparing the incoming dateOfBirth variable against these dates, and returns a new instance of either a new Infant, Child, or Adult class.