使用接口进行数据隐藏
我有一个接口 I,有两个方法 func A 和 func B 以及一个带有接口实现的类 C,我有两个用户 U1 和 U2。 我想要的功能是,如果 u1 访问类 C,则应调用 func A,如果 u2 访问类 C,则应调用 func B。 我如何使用 OOP 来实现这个?
I have an interface I with two methods func A and func B and a class C with the implementation of the interface, I have two users U1 and U2.
I want the functionality so that if u1 accesses class C, func A should be called and if u2 accesses class C func B should be called.
How do i implement this using OOPs ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为你真正想要的是:
示例 比方
说:
通过这种方式,您可以调用:
这是纯粹的 OOP,我认为以 TDD 方式编写非常简单。
I think that what you really want is:
Example
Let's say:
In this way you can call:
This is pure OOP and I think it's pretty simple to write in a TDD fashion.
我将重点关注您提出的问题。为什么您想要这样做以及这对于面向对象设计原则是否确实是一个好主意是另一个问题。
首先,您的要求类似于以下内容:(note)
现在,让我们创建一个
User
角色以及用户 1 和 user 的两个实现2:最后,如下实例化您的用户 1 和 2:
并按如下方式“访问”您的 C:
请注意,此代码几乎完全将类
C
排除在游戏之外,而是专注于接口(<代码>I)。但是,如果您希望代码专门与C
配合使用,只需在适当的位置将I
替换为C
(即使用参数方法Access
)。(注意:) 我选择了 C# 作为示例,但翻译成您选择的语言应该很容易。
I will focus on what you've asked. Why you would want to do this and whether it's actually a good idea with respect to OO design principles is another question.
First, your requirement would look similar to the following: (note)
Now, let's create a
User
role and two implementations for user 1 and user 2:Finally, instantiate your users 1 and 2 as follows:
And "access" your C as follows:
Note that this code almost completely leaves class
C
out of the game and instead focuses on the interface (I
). If, however, you want your code to work specifically withC
, simply replaceI
withC
in the appropriate place (namely, with the parameter of methodAccess
).(note:) I've chosen C# for the examples, but translating to the language of your choice should be easy.
肯定需要更多的澄清来确定你想要做什么,但是......
而不是在 User 类中使用逻辑,像 OO 一样思考,也许是一个工厂,比如:
这有一个好处是允许用户保持简单,其中没有业务代码。工厂只需足够聪明,知道它想要根据用户创建哪个 C。调用真实方法的所有实际工作都是在 C 本身中完成的。
编辑:您可能需要稍微修改一下接口和 C 类 - 在这种情况下,您需要 CallMethod() 方法位于接口中。或者你的工厂可以返回 C 而不是 I。当然,在不了解整个故事的情况下,很难说哪个是正确的。
More clarification is definitely needed to determine exactly what you're trying to do, but...
Rather than having the logic in the User class, thinking OO-like, maybe a factory, like:
This has the benefit of allowing the user to remain simple with no business code in it. The factory has to only be smart enough to know which C it wants to create based on the user. All of the actual work of calling the real method is done in the C itself.
EDIT: You may have to fiddle with the interface and the C class a little - in this case, you'd need the CallMethod() method to be in the interface. Or your factory could return a C instead of an I. Of course, without knowing the whole story, it's hard to say which is correct.