具有不同类型用户的 Java 应用程序:我应该使用层次结构吗?
我正在构建一个小型应用程序来学习具有不同类型用户的Java。起初,我认为这是一个层次结构,用户是超级阶级和其他三个(客户,管理员和工作人员)子类。另外,这三种用户类型具有不同的方法和GUI,但是它们都有用户和密码。
我的问题是,我有一个名为“应用程序”的类,以及返回用户对象的方法登录,我不知道该对象是不使用instanceof的admin,worker还是客户。同样,所有方法都在每个子类中,同样,我不想使用实例。我有另一个想法是在用户类中制作所有方法,以及我将检查的角色枚举,以查看用户是否有许可。但是,如果我需要为此进行枚举,我看不到拥有子类的意义。
有什么解决方案吗?
注意:这是一个小应用程序,没有数据库或在线连接,只有一个大学项目。
I'm building a small application to learn Java that has different types of user. At first, I thought that It was a hierarchy, where user is the superclass and the other three (customer, admin and worker) subclasses. Also, this three user types have different methods and GUIs, but they all have user and password.
My problem is that I have a class called Application and the method login that returns an user object and I don't know how to see if this object is an admin, worker or customer without using instanceof. Also, all the methods are in each subclass because they don't have functionality in common, except the login (that is in another class), then if I have an object of type user I would need to cast it to another subclass, but, again, I don't want to use instanceof. Another idea that I had is to make all the methods in user class and an role enum that I would check to see If the user has permission. But, If I need to do an enum for this, I don't see the point in having subclasses.
Is there any solution to this?
Note: It's a small app, without databases or online connection, only a college project.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从我的所有经验来看,为用户提供多个类是一个不好的主意:
事实证明,另一点更难实施:当前角色的一个枚举参考。尽管这是一个很好的解决方案,但请考虑特殊的权限和角色混合(
set< myroleenum>
或set< myroleclass>
)。FATIT:
此(用户在迄今为止,我已经实施了最新项目的列表/一组枚举角色),这是我最新的最新项目的最好的,故障的(编译时间安全)模型。
user.set< myroleenum>
的最大缺点是,您必须重新编译+重新编译整个代码以扮演其他角色。但是其他角色通常总是带有新功能,因此必须重新编译/部署该代码...如果您的项目打算由成千上万的用户和一组管理员使用,请选择
user.set< myroleclass>
实现。Myroleclass
的实例,持久性和管理中进行许多其他工作
From all my experience, it's quite a bad idea to have multiple classes for the User:
Another point which has proven to make implementation harder: one enum reference for the current role. Although this is quite a good solution, think about special permissions and a mixture of roles (
Set<MyRoleEnum>
orSet<MyRoleClass>
).Facit:
This (user has a list/set of enum roles), so far, has proven the best, fail-safe (compile-time safe) model I have implemented up to date, for smaller projects.
User.Set<MyRoleEnum>
is that you have to recompile+redeploy the whole code for an additional role. But additional roles usually always come with new features, so the code would have to be re-compiled/deployed anyway...If your project is meant to be used by thousands of users and an army of admins, go for the
User.Set<MyRoleClass>
implementation.MyRoleClass