库设计-限制“实习生”使用的模式类/方法
我偶然发现了一个小型库,其中包含四个包中的一些类和一个基本类,任何使用该库的人都应该使用这些类。
我必须审查这个库并建议,对某些类和方法的访问应该受到限制,因为用户应该只看到他真正应该使用的方法/类。在这种情况下,它应该是一个具有一些可以调用的方法的类。
虽然我的建议刚刚出现在我的脑海中,但我无法找到真正的解决方案。
第一个丑陋的想法是:将公共类放在包 a
中,并将其他所有内容放在包 ab
中,这不是一个好主意。
包结构阻止了 protected
修饰符,因为包 ab
中的类需要调用包 ac
中类的方法。那么是否有一种模式可以用来防止有人在 ab
中实例化一个类并调用其公共方法?
如果问题的描述不够好,请随时在评论中提问。谢谢。
I stumbled upon a small library which has some classes in four packages and one basic class that should be used by who ever will use this library.
I had to review this library and suggested, that the access to some classes and methods should be restricted as the user should only see methods/classes that he really should use. In this case it should be one class with a few methods that can be called.
While my suggestion just popped into my mind, I couldn't get a real solution on how to do that.
The first ugly idea was: Put the public class in package a
and everything else in package a.b
which isn't a good idea.
The package structure prevent the protected
modifier as classes in package a.b
need to call methods from a class in package a.c
. So is there a pattern that can be used to prevent that someone is instantiating a class inside a.b
and call their public methods?
If the description of the problem wasn't good enough, feel free to ask in the comments. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
虽然我不明白你关于受保护访问修饰符的句子(b和c不是已经打包了吗?)这里有两个建议:
InterfacePackA
、InterfacePackB
,因此客户端代码将保存您的接口类型偏好下的主类减少了相当通用且有瓶颈的主类的范围和功能。Although I don't understand your sentence about the protected access modifier (aren't
b
andc
already packaged?) here are two suggestions:InterfacePackA
,InterfacePackB
that your main class would implement and therefore the client code would hold your main class under the interface type of preference reducing this way the scope and functionality of the quite generic and bottlenecked main class.使用默认修饰符放置您不希望其他人看到的类(基本上根本不使用修饰符)。这将使它们成为包私有的。
包内的所有类都将能够看到和使用它们,但库外部的任何人都无法在没有反射作弊的情况下实例化和使用它们。
这意味着库应该使用单个包。
Put classes that you don't want other people to see with default modifier ( basically with no modifier at all ). This will make them package-private.
All classes inside the package will be able to see and use them, but nobody outside the library would be able to instantiate and use them without reflection cheats.
This implies that library should use a single package.
将人们不应该用作
私有静态
类的类放在主类中。Put the classes that people should not use as
private static
classes inside the main class.Java 无法阻止 jar 中的公共类被调用。如果您通过混淆其他类来隐藏它们的功能,那么您可以给出您的 jar 并仅公开您想要使用的某些类。这不会导致无法使用您的公共类,但会花费比可能值得的更多工作。
Java has no way of stopping public classes in a jar from being called. If you hide what the other classes do by obfuscating them, then you could give out your jar and only expose certain classes that you wanted used. This would not make it impossible to use your public classes, but would take more work than it is probably worth.