Java - 更改引用变量
所以我知道引用变量不能更改。
我所处的位置有两个不同的班级。我们称它们为 A 和 B。它们具有相同的方法(方法的名称相同),只是为类指定的。
我需要一种巧妙的方法来更改要实例化的类。
一种方法是使用一些布尔测试来检查已选择哪个选项,然后实例化相应的类。虽然我担心这可能会变得笨重和丑陋,所以我试图避免这种方式。一定有更聪明的事情。
目前我正在考虑创建一个新类(例如C)来扩展与A和B相同的类。
然后我将重写这些方法(因为A类和B类也这样做),然后根据设置执行这些方法(即选择 A 类或 B 类)。这些方法将返回与 A 类或 B 类中相同的结果。
希望我不是在胡言乱语。
So I know that reference variables cannot be changed.
I'm in a position where I have two different classes. Let's call them A and B. They have the same methods (the methods are called the same) they're just specified for the class.
I need a clever way of changing between which classes to instantiate.
One way could be with some boolean tests checking which option has been selected and then instantiate the corresponding class. Although I fear that this might become bulky and ugly, so I'm trying to avoid this way. There must be something more clever.
Currently I'm thinking of making a new class (e.g. C) that extends the same class as A and B.
I would then override the methods (as class A and B also do btw) and then execute the methods depending on the setting (i.e. which class A or B is selected). The methods would return the same as it would in class A or B.
Hope I'm not talking complete gibberish.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种方法是使用工厂模式。
部分引用自维基百科:
例如
One way to do this is to use the Factory Pattern.
Partial quote from Wikipedia:
E.g.
你的解释令人困惑。但听起来您应该从公共基类(或接口)扩展
A
和B
:这意味着您可以执行以下操作:
Your explanation is confusing. But it sounds like you should extend
A
andB
from a common base class (or an interface):That means you can do something like this: