[英]one to one relationship between classes in java
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. 我必须在Java SE中实现以下类,但无法弄清楚如何实现ATMCard和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
: 首先,我发现您的模型对于
ATMCard
和Account
有点奇怪:
PIN
related to the ATMCard
rather than to the Account
? PIN
与ATMCard
而非Account
吗? custName
related the Account
? custName
与Account
是否相关? Then, the 1-1 relationship means you will have one of these: 然后,1-1关系意味着您将具有以下之一:
Account
class has a member of type ATMCard
Account
类具有ATMCard
类型的成员 ATMCard
class has a member of type Account
ATMCard
类的成员类型为Account
ATMCard$getAccount()
that will retrieve the related Account
based on the accountNo
. ATMCard$getAccount()
,该ATMCard$getAccount()
将根据accountNo
检索相关的Account
。 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 正如@NickHolt所建议的那样,我将选择一种可以通过工厂初始化的单向关系船,例如
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. 您可以保护
ATMCard
和Account
构造函数以强制使用public factory方法。
Note: you can use a framework like Spring
or Guice
to provide this kind of factory and injection service. 注意:可以使用
Spring
或Guice
类的框架来提供这种工厂和注入服务。
要在ATMCard
和Account
之间创建一对一关系,您必须在ATMCard
类中创建Account
实例。
The way I see this is ATM
doesn't need to be related to ATMCard
or the Account
. 我认为这是
ATM
的方式不需要与ATMCard
或Account
。 Think about what happens you bank ATMCard
is used in ATM
of other bank? 想一想您的银行
ATMCard
在其他银行的ATM
中使用会怎样? Or you bank doesn't allow the ATMCard
be used in other bank ATM
否则您的银行不允许将
ATMCard
用于其他银行的ATM
These should part of withdrawal operation of the ATM. 这些应该是自动柜员机提款操作的一部分。
You could have a bidirectional relationship from Account
to ATMCard
您可能有一个从
Account
到ATMCard
的双向关系
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.