在学习了设计模式之后,想用现实中的例子来应用一下。下面是我想到的一个代理模式实际应用的例子。
模拟了一个贷款买房人向银行申请贷款时,银行审批的处理.
新建一个申请贷款买房的接口
package loans_package;
public interface apply_for_loans_package
{
public void apply_for_loans();
}
新建一个买房者类,具有买房的能力,所以实现接口apply_for_loans_package
package loans_package;
public class people implements apply_for_loans_package
{
private int salary;
private String userName;
public int getSalary()
{
return salary;
}
public void setSalary(int salary)
{
this.salary = salary;
}
public String getUsername() {
return userName;
}
public void setUsername(String username) {
this.userName = username;
}
public void apply_for_loans()
{
System.out.println(userName+"要申请贷款买房");
}
}
people类必须经过银行工作人员这个代理类的认证,工资符合贷款条件之后才可以
贷款。新建一个代理类,这个代理类来考察当前的people是否有资格进行贷款买房。
package loans_package;
public class proxy_bank_staff implements apply_for_loans_package
{
private people people;//申请贷款人
private int monthly_payments;//房贷月供
public int getMonthlyPayments()
{
return monthly_payments;
}
public void setMonthlyPayments(int monthly_payments)
{
this.monthly_payments = monthly_payments;
}
public people getPeople() {
return people;
}
public void setPeople(people people) {
this.people = people;
}
public void apply_for_loans()
{
if(people.getSalary()>=2*monthly_payments)
{
System.out.println("恭喜"+people.getUsername()+",通过了银行贷款审批!");
}
else
{
System.out.println("对不起 "+people.getUsername()+"的贷款资格不够,望继续努力!");
}
}
}
最后创建一个客户端,用来模拟贷款买房审批的行为:
package loans_package;
public class run_main {
public static void main(String[] args) {
//新建一个申请贷款买房人
people people_ref = new people();
//姓名
people_ref.setUsername("刘红梅");
//工资数
people_ref.setSalary(6000);
//新建一个银行职员代理类
proxy_bank_staff proxyer = new proxy_bank_staff();
//设置贷款申请人
proxyer.setPeople(people_ref);
//设置申请月供
proxyer.setMonthlyPayments(5000);
//银行审批
proxyer.apply_for_loans();
//申请贷款人涨工资了
proxyer.getPeople().setSalary(10000);
//银行再次审批
proxyer.apply_for_loans();
}
}
程序的运行结果如下:
对不起 刘红梅的贷款资格不够,望继续努力!
恭喜刘红梅,通过了银行贷款审批!
是不是很有意思:)