码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式-工厂方法模式

时间:2019-06-08 13:11:13      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:amount   alc   代码   ati   系统   bst   ext   abs   模式   

整理了一下基础知识,之前做银行系统时比较频繁的用过工厂方法。

//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自己去确定具体有那个对象来实现方案。





设计模式-工厂方法模式

标签:amount   alc   代码   ati   系统   bst   ext   abs   模式   

原文地址:https://www.cnblogs.com/payzulla/p/10990325.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!