内部接口——暴露我的无知
我知道这些 两个 问题解释了为什么我不能在接口中使用受保护/私有方法,我正在尝试做什么out 是如何控制从哪里调用我的方法,简单地说:
public class EditField : IEditField
{
public EditField() {}
public EditField(IStateMachine stateMachine) {}
public void Action_Commit() {}
public void Action_Undo() {}
}
消费者可以使用默认的 IStateMachine,或者推出自己的 IStateMachine。
我想知道是否有任何方法可以确保 Action_ 方法仅从 IStateMachine 内调用,这样消费者就不会开始搞乱状态的东西。 我怀疑没有办法做到这一点,但想知道我是否错过了一些东西。 我不是设计模式大师。
I'm aware of these two questions which explain why I can't have a protected/private method in an interface, what I'm trying to work out is how to control from where my methods are called, briefly:
public class EditField : IEditField
{
public EditField() {}
public EditField(IStateMachine stateMachine) {}
public void Action_Commit() {}
public void Action_Undo() {}
}
Consumers can use the default IStateMachine, or roll their own.
I was wondering if there is any way to ensure that Action_ methods are only called from within an IStateMachine, so that consumers don't start messing around with state stuff. I suspect there's no way of doing this, but wondered if I'm missing something. I'm not a Design Pattern guru.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不确定我明白你想做什么。 但为了隐藏东西,我通常显式地实现接口。 如果某人需要访问某些内容而不需要访问其他内容,您可能还应该将界面分成两个或其他内容。
I'm not sure I understand what you want to do. But to hide stuff I usually implement interfaces explicitly. If someone needs access to some things and not to others, you should also probably split the interface into two or something.
虽然您不能在接口上拥有访问修饰符,但这是隐藏成员的一种方法,但又使 IStateMachine 实现者可以访问它们。
While you can't have access modifiers on interfaces, but here's one way to hide the members, yet make them accessible to IStateMachine implementors.
嗯,您可以做的是通过显式实现这些方法来“隐藏” Action_ 方法。
如果这样做,用户只能在将类强制转换回接口时调用这些方法。
然而,这不会阻止他们调用这些方法的可能性,但也许它会让人们不太明显地意识到这是可能的。
通过像这样实现这些方法,用户将无法执行此操作:
但是,如果他们这样做,则可以调用这些方法:
或者
但是,这不是一个更好的解决方案/可以让这些 Commit & 撤消方法是 IStateMachine 的一部分吗?
而且,如果您无法修改设计以实现这些提交和提交, 撤消 IStateMachine 的方法部分,那么也许您可以创建一个抽象类而不是 IEditField 接口?
在该抽象类中,您可以使这些 Action_ 方法受到保护。
Hmm, what you can do is 'hide' the Action_ methods by implementing those methods explicitly.
If you do this, users can only call those methods when they cast the class back to the interface.
It won't prevent them from having the possibilty to call those methods however, but maybe it will make it less obvious that it is possible.
By implementing these methods like this, the user will not be able to do this:
However, it is possible to call those methods if they do this:
or
But, isn't it a better solution / possible to have those Commit & Undo methods a part of your IStateMachine instead ?
And, if you can't modify the design to have those Commit & Undo methods part of the IStateMachine, then maybe you can create an abstract class instead of the IEditField interface ?
In that abstract class, you can make those Action_ methods protected.