内部接口 - 暴露我的无知 [英] Internal interfaces - exposing my ignorance

查看:129
本文介绍了内部接口 - 暴露我的无知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这些 两个问题解释了为什么我在界面中没有受保护/私有方法,我是什么试图解决的是如何控制从哪里调用我的方法,简要说明:

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() {}
}

消费者可以使用默认的IStateMachine,也可以自己滚动。

Consumers can use the default IStateMachine, or roll their own.

我想知道是否有任何方法可以确保只从IStateMachine中调用Action_方法,这样消费者就不会开始搞乱状态。我怀疑没有办法做到这一点,但我想知道我是否遗漏了一些东西。我不是设计模式大师。

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.

推荐答案

虽然你不能在接口上拥有访问修饰符,但这里有一种方法隐藏成员,但让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.

public interface IEditActions
{
  void Action_Commit() {}
  void Action_Undo() {}
}

public interface IStateMachine
{
  void Initialize(IEditActions editActions);
}

public class EditField : IEditField
{
  private class EditActions : IEditActions
  {
    EditField _editField;

    public EditActions(EditField editField)
    {
      _editField = editField;
    }

    public void Action_Commit()
    {
      _editField.Action_Commit();
    }
    public void Action_Undo()
    {
      _editField.Action_Undo();
    }
  }

  public EditField() {}
  public EditField(IStateMachine stateMachine)
  {
    stateMachine.Initialize(new EditActions(this));
  }

  private void Action_Commit() {}
  private void Action_Undo() {}
}

这篇关于内部接口 - 暴露我的无知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆