Java 的“朋友”等价物?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/376427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:02:08  来源:igfitidea点击:

'Friends' equivalent for Java?

javadesign-patternsfriend

提问by Alex Lim

having a little architectural trouble here.

这里有一点架构问题。

In C++, we have the notion of 'friends,' where such friend classes can access private members.

在 C++ 中,我们有“朋友”的概念,这样的朋友类可以访问私有成员。

So, I'm deving a Java app and trying to adhere to the MVC architecture. I've got a controller class that manages graph connectivity between 'map_objects.' I'd like to hide the function in the DTO 'map_objects' that actuall sets up these connectivities, by using this controller class.

所以,我正在开发一个 Java 应用程序并尝试遵守 MVC 架构。我有一个控制器类,用于管理“map_objects”之间的图形连接。我想通过使用这个控制器类隐藏实际设置这些连接的 DTO 'map_objects' 中的函数。

(Ie, even if the controller class implements the required functionality of setting up connectivities, the 'users' can still access setter/getter functions in the the DTO directly to set them up themselves.)

(即,即使控制器类实现了设置连接所需的功能,“用户”仍然可以直接访问 DTO 中的 setter/getter 函数以自行设置它们。)

Are there any design patterns or tips in this regard? (Or have I totally mucked up?)

在这方面是否有任何设计模式或提示?(还是我完全搞砸了?)

DUPLICATEIs there a way to simulate the C++ 'friend' concept in Java?

DUPLICATE有没有办法在 Java 中模拟 C++“朋友”概念?

采纳答案by Julien Chastang

(Un)fortunately, there is no direct C++ friend equivalent in Java. However, the Java access level modifierscan assist you. In particular, private or package private (AKA package protected, or "default") may help.

(不)幸运的是,Java 中没有直接的 C++ 朋友等价物。但是,Java 访问级别修饰符可以为您提供帮助。特别是,私有或包私有(AKA 包保护,或“默认”)可能会有所帮助。

回答by Ilja Preu?

You might want to use interface segregation- that is, let the class implement different interfaces, and only pass out references to the appropriate (smaller) interfaces to the different clients.

您可能想要使用接口隔离——也就是说,让类实现不同的接口,并且只向不同的客户端传递对适当(较小)接口的引用。