在被动视图模式中创建子视图

时间:2010-02-12 20:20:09

标签: design-patterns passive-view

我对使用Passive View模式提高可测试性非常感兴趣,但我不确定如何调用子对话框。

您是否有父视图创建子视图并将接口返回到父控制器,然后让父控制器创建子控制器?

1 个答案:

答案 0 :(得分:1)

我一直在考虑这个问题,我想我有几个可能的解决方案。

  1. 向视图类添加方法以生成从属对话框
  2. 创建一个生成模型视图的工厂。和从属对话框的控制器
  3. 方法1

    class ParentView extends JDialog implements IParentView {
      public IChildView newChildView(...) {
        return new ChildView(...);
      }
      // ...
    }
    
    interface IParentView {
      IChildView newChildView(...);
      // ...
    }
    
    class ParentController {
      private IParentView view;
      public ParentController(IParentView view) {
        this.view  = view;
      }
    
      public void showChildView() {
        IChildView childView = view.newChildView();
        ChildController childController = new ChildController(childView);
        childView.setVisible(true);
      }
    }
    
    class ChildView extends JDialog implements IChildView {
      // ...
    }
    
    interface IChildView {
      void setVisible(boolean visible);
    }
    
    class ChildController {
      private IChildView view;
      public ChildController(IChildView view) {
        this.view = view;
      }
    }
    

    方法2

    // During testing, create a mock ChildFactory and assign it to instance
    class ChildFactory implements IChildFactory {
        private static IChildFactory instance;
        public static ChildFactory getInstance() {
          if (instance == null) {
            instance = new ChildFactory();
          }
          return instance;
        }
        public static void setInstance(IChildFactory factory) {
          instance = factory;
        }
        public void createChild(IParentView parent) {
          IChildView view = new ChildView(parent);
          ChildController controller = new ChildController(view);
          view.setVisible(true);
        }
    }
    
    interface IChildFactory {
      void createChild(IParentView parent);
    }
    
    class ParentController {
      private IParentView view;
      public ParentController(IParentView view) {
        this.view  = view;
      }
      public void showChildView() {
        ChildFactory.getInstance().createChild(view);
      }
    }
    
    // ParentView class similar to method 1