Search⌘ K

Challenge: Solution Review

Explore how to apply the abstract creational pattern to dynamically instantiate different types of loan objects in JavaScript. Learn how constructors for personal, student, and home loans encapsulate properties and methods for calculating interest, simplifying object creation while enhancing code organization.

We'll cover the following...

Solution #

Node.js
function HomeLoan(amount,duration){
this.amount = amount
this.interest = 0.08
this.duration = duration
this.calculateInterest = function(){
return this.amount*this.interest*this.duration
}
}
function StudentLoan(amount,duration){
this.amount = amount
this.interest = 0.03
this.duration = duration
this.calculateInterest = function(){
return this.amount*this.interest*this.duration
}
}
function PersonalLoan(amount,duration){
this.amount = amount
this.interest = 0.05
this.duration = duration
this.calculateInterest = function(){
return this.amount*this.interest*this.duration
}
}
function Loans(){
this.getloan = function(type,amount,duration){
var loan;
switch(type){
case 'home':
loan = new HomeLoan(amount,duration)
break;
case 'student':
loan = new StudentLoan(amount,duration)
break;
case 'personal':
loan = new PersonalLoan(amount,duration)
break;
default :
loan = null
break;
}
return loan
}
}
var loan = new Loans()
var homeLoan = loan.getloan('home',3200,5)
console.log(homeLoan.calculateInterest())
var studentLoan = loan.getloan('student',1800,4)
console.log(studentLoan.calculateInterest())
var personalLoan = loan.getloan('personal',1200,2)
console.log(personalLoan.calculateInterest())

Explanation

To make the problem easier to understand, let’s start by converting it to a diagram.

If you follow the diagram and the code, you’ll see that there is an abstract Loans constructor function. Its purpose is to instantiate an instance of a specific loan constructor, depending on the parameters given.

From the diagram above, you can see that three types of loan objects can be instantiated:

  • PersonalLoan

  • StudentLoan

  • HomeLoan

These loans, in turn, have different types available. In our coding challenge, we do not go into these subcategories. However, knowing this will ...