设计模式-工厂方法模式
整理了一下基础知识,之前做银行系统时比较频繁的用过工厂方法。
//first, we need to create a LoanType abstract class
abstract class LoanType {
protected double rate;
abstract void getRate();
public void calculateAmount(int units){
System.out.println(rate * units);
}
}
//then the class what will extends the LoanType
public class CarLoan extends LoanType {
@Override
void getRate() {
rate = 5.00;
}
}
public class StudentLoan extends LoanType{
@Override
void getRate() {
rate = 4.50;
}
}
public class CommercialLoan extends LoanType {
@Override
void getRate() {
rate = 7.80;
}
}
//Third, we should create the class to make sure which kind of loan will be taken
public class ChooseLoanTypeFactory {
public LoanType getLoanType(String loanType) {
if (loanType == null) {
return null;
}
if (loanType.equalsIgnoreCase("StudentLoan")) {
return new StudentLoan();
} else if (loanType.equalsIgnoreCase("CarLoan")) {
return new CarLoan();
} else if (loanType.equalsIgnoreCase("CommercialLoan")) {
}
return new CommercialLoan();
}
}
//Last, create the class for generation of loan
public class ChooseLoanTypeFactory {
public LoanType getLoanType(String loanType) {
if (loanType == null) {
return null;
}
if (loanType.equalsIgnoreCase("StudentLoan")) {
return new StudentLoan();
} else if (loanType.equalsIgnoreCase("CarLoan")) {
return new CarLoan();
} else if (loanType.equalsIgnoreCase("CommercialLoan")) {
}
return new CommercialLoan();
}
}
现实的交易中,贷款类型不同,那利率以及优惠试算方式,期限以及其他辅助产品及调价方式会不同,因此每个类都有自己单独的属性以及行为验证。
设计模式-顾名思义就是为了去解决某一类问题而产生的且已被验证为比较高效的-套路。
工厂模式充分体现面向对象的特质,即与现实生活中对象与代码中的结合。我们有一类方案,可对应的具体对象对该方案的实现是不确定,即不同的对象有差异。
所以方案本身不确定那种对象来实现它的时候,工厂模式就诞生了。就让sub-class自己去确定具体有那个对象来实现方案。