您的位置:首页 > 其它

简单 Proxy 自动提款机应用

2014-06-04 00:00 169 查看
摘要: Proxy

Input输入类:

import java.util.Scanner;

public class Input {

private ProxyAccount account;

public Input(ProxyAccount account) {
super();
this.account = account;
}

public void startInput() {
String p = account.enterPIN();
if(p.equals(account.getPIN())){

Scanner scanner = new Scanner(System.in);
String c = "a";
while (!c.equals("x")) {
System.out.println("Enter");
System.out.println(" w to withdraw money");
System.out.println(" d to deposit money");
System.out.println(" x to quit");
System.out.print("Choice: ");
c = scanner.next();
if (c.equals("w") || c.equals("d")) {
int amount = 0;
System.out.print("Amount: ");
amount = scanner.nextInt();
if (c.equals("w")) {
account.withdraw(amount);
System.out.println("New amount: " + account.getAmount());
} else if (c.equals("d")) {
account.deposit(amount);
System.out.println("New amount: " + account.getAmount());
}
}
}
}
else{
System.out.println("Your password is false!");
this.startInput();
}
}

}

-------------------------------------------------------------------------------------------------------------------------------

RealAccount 实际Subject类:

public class RealAccount implements Account{

private int amount;

public RealAccount(int amount) {
super();
this.amount = amount;
}

public void withdraw(int money) {
amount = amount - money;
}

public void deposit(int money) {
amount = amount + money;
}

public int getAmount() {
return amount;
}

}

-------------------------------------------------------------------------------------------------------------------------------

ProxyAccount 代理类:

import java.util.Scanner;

public class ProxyAccount implements Account{

private Account proxied;

private String PIN;

public ProxyAccount(Account proxied, String PIN) {
super();
this.proxied = proxied;
this.PIN = PIN;
}

public String getPIN() {
return PIN;
}

public String enterPIN(){
Scanner pin = new Scanner(System.in);
System.out.print("Please enter your password: ");
return pin.next();
}

public void deposit(int money) {
proxied.deposit(money);

}

public int getAmount() {
return proxied.getAmount();
}

public void withdraw(int money) {
proxied.withdraw(money);

}

}

-------------------------------------------------------------------------------------------------------------------------------

Account 接口:

public interface Account {

void withdraw(int money);

void deposit(int money);

int getAmount();

}

-------------------------------------------------------------------------------------------------------------------------------

Main 主方法:

public class MainAccount {

public static void main(String[] args) {
Account account = new RealAccount(5000); //多态
ProxyAccount proxyaccount = new ProxyAccount(account,"123456");
Input input = new Input(proxyaccount);
input.startInput();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Proxy 简单实例
相关文章推荐