I have to implement following classes in Java SE but I cannot figure out that how can I achieve the one-to-one relationship between ATMCard and Account. I have researched (may be with wrong keywords) but could not find anything. Thank you in advance..
First, I find your model a bit strange for ATMCard
and Account
:
PIN
related to the ATMCard
rather than to the Account
? custName
related the Account
? Then, the 1-1 relationship means you will have one of these:
Account
class has a member of type ATMCard
ATMCard
class has a member of type Account
ATMCard$getAccount()
that will retrieve the related Account
based on the accountNo
. It really depends on the model logic you need.
As @NickHolt suggests, I would go for a one-way relation ship you can initialise through a factory, eg
public static ATMCard createCard(String name, int accNo, int pin, int initBal) {
Account acc = new Account(name, accNo, initBal);
ATMCard card = new ATMCard(pin);
card.setAccount(acc);
return card;
}
You can have ATMCard
and Account
constructors protected to enforce the use of the public factory method.
Note: you can use a framework like Spring
or Guice
to provide this kind of factory and injection service.
要在ATMCard
和Account
之间创建一对一关系,您必须在ATMCard
类中创建Account
实例。
The way I see this is ATM
doesn't need to be related to ATMCard
or the Account
. Think about what happens you bank ATMCard
is used in ATM
of other bank? Or you bank doesn't allow the ATMCard
be used in other bank ATM
These should part of withdrawal operation of the ATM.
You could have a bidirectional relationship from Account
to ATMCard
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.