我必须实施信用卡申请,我必须只处理一个信用卡帐户。 credit()
,debit()
,pinChange()
等操作。
但问题是我必须使用“JAVA CALLBACK”机制在两种情况下通知用户:
如何对这些通知使用回调?
CALLBACKS的使用更受关注..
public interface Callback {
public void onPinChange();
public void onLowBalance();
}
import java.util.Scanner;
public class CreditCard implements Callback{
Callback callback;
int pin;
float balance;
public CreditCard() {
callback = this;
this.pin = 1234; // default pin
this.balance = 10000f; // opening balance
}
public void creditBalance(float amount) {
this.balance = this.balance + amount;
}
public void debitBalance(float amount) {
if (balance <= amount) {
System.out.println("Not enough balance to debit");
} else {
balance = balance - amount;
}
if (balance < 5000) {
callback.onLowBalance();
}
}
public void changePin(int newPin) {
System.out.println("Enter the current pin");
Scanner scanner = new Scanner(System.in);
int existingPin = scanner.nextInt();
if (existingPin != pin) {
System.out.println("Wrong pin!");
} else {
pin = newPin;
callback.onPinChange();
}
scanner.close();
}
@Override
public void onPinChange() {
System.out.println("Pin changed");
}
@Override
public void onLowBalance() {
System.out.println("low balance");
}
public static void main(String[] args) {
CreditCard card = new CreditCard();
card.changePin(3333);
card.debitBalance(5200);
}
}
答案 0 :(得分:6)
更改Pin并获得低平衡是CreditCard的行为,因此CreditCard对象是事件生产者而非事件监听器,因此您不希望将CreditCard设置为侦听器(CallBack)。
实际上,当发生任何类似pinChange或lowBalance的事件时,您的CreditCard将调用您想要通知的侦听器的方法。
您的代码应如下所示:
class CreditCard{
int pin, balance;
private Callback callback;
CreditCard(Callback callback){
this.callback=callback;
}
public void pinChange(int pin){
this.pin=pin;
//inform the listener as well
callback.pinChanged();
}
public void withdraw(int amount){
this.balance-=amount;
//inform the the listener
if(balance<1000)callback.lowBalance();
}
}
class MyListener implements Callback{
public void pinChanged(){
//do what is needed when somebody changes pin..
//i.e send sms to the customer
System.out.println("PIN changed..");
}
public void lowBalance(){
//inform the customer about lowbalance.
System.out.println("little money in card..");
}
main(String... args){
CreditCard cc=new CreditCard(new MyListener());
cc.changePin(3306);
}
}
希望这一点清楚......
答案 1 :(得分:1)
如果你只需要为每个事件进行一次回调(我称之为监听器),那么你可以这样做(我只显示两个监听器中的一个,另一个看起来非常相似) :
public interface PinChangeListener {
public void pinChanged();
}
public CreditCard {
public PinChangeListener pinChangeListener;
private int pin;
public changePin(int pin) {
this.pin = pin;
if (pinChangeListener != null) {
pinChangeListener.pinChanged();
}
}
}
为简单起见,我将侦听器字段公之于众。我更喜欢使用setter,然后我想你知道它是如何工作的。
要将回调/侦听器连接到信用卡,您只需实施PinChangeListener
方法:
creditCard.pinChangeListener = new PinChangeListener() {
public void pinChanged() {
System.out.println("The pin has been changed");
}
};
您可以轻松转换代码以支持每个事件的多个侦听器。只需使用一个监听器列表。通常,您希望编写addPinChangeListener
,removePinChangeListener
和triggerPinChanged
等方法。
答案 2 :(得分:0)
几点: