【发布时间】:2020-04-23 23:44:44
【问题描述】:
我想编写一个跟踪银行帐户的 java 程序
现在我有以下简单的程序:
public class account
{
private double balance;
private String owner;
public account(double x, String s) { balance=x; owner=s; }
public String owner() { return owner; }
public void withdraw(double a) { balance -= a; }
public void deposit(double a) { balance += a; }
public void printbalance() { System.out.println(balance); }
// main for testing:
public static void main(String[] argv)
{
account a1 = new account(2000,"you boss");
account a2 = new account(1000,"me nerd");
a1.deposit(400);
a2.withdraw(300000); // not enough money!
a2.withdraw(-500000); // trying to cheat!
a1.printbalance();
a2.printbalance();
}//main
} // account
我想使用 aspectj 在这个程序中添加以下内容:
1-我想阻止账户提取更多的当前余额并提取负数。
2- 我也希望它防止存入负数。
3- 我需要添加一个图形界面,(按钮)
4- 添加在客户进行交易之前需要输入的密码或密码。
5- 跟踪账户上的所有交易(提款和存款),并在需要时打印报告。
感谢您的帮助。谢谢。
privileged aspect newAccount
{
//withdraw (prevent withdraw negative numbers and number greater than the //current balance)
void around(account a, double x) : execution(void account.withdraw(double)) && target(a) && args(x){
if(x > a.balance){
System.out.println("not enough money!");
return;
}else if(x < 0){
System.out.println("trying to cheat!");
return;
}
proceed(a, x);
}
//Deposit: prevent deposit negative number
void around(double x) : execution(void account.deposit(double)) && args(x){
if(x < 0){
System.out.println("trying to deposit negtive money!");
return;
}
proceed(x);
}
after() : execution(public static void *.main(String[])){
account.a3 = new account(3000,"he nerd");
a3.deposit(-100);
a3.printbalance();
}
//To Do: pin secret password
//To Do: Transaction Record
}
【问题讨论】:
-
1、2 和 4 和 5 级可以在没有 AOP 的情况下做得更好。我不知道 AspectJ 对 3 有什么用处。如果您只想练习 AspectJ,official documentation 中有一些示例可以帮助您入门。
-
我不同意。我会排除 3,因为 GUI 不是一个方面。但是1、2、4、5可以通过AOP实现(当然也可以不用)。至于 GUI,也许 GUI 和后端之间的通信(通知、事件)也可以通过 AOP 完成。但是,让我们跳过自以为是的讨论,直奔主题:我是否正确地假设这是某种家庭作业,而它的全部意义在于使用 AOP?
-
是的,大部分。 @kriegaex
-
那么你尝试了什么,你的问题在哪里?请显示一些方面的代码。或者您是否希望这里有人为您完成家庭作业?你可以付钱给我,但我有一种感觉,你宁愿免费获得信息,最好不要自己做任何工作。
-
我添加了我到目前为止所做的事情。对造成的不便表示歉意。我只是想了解aspectj,因为我还在学习Java。我将不胜感激任何帮助。谢谢你。 @kriegaex