gpt4 book ai didi

java - 良好的 MVC 设计,用于由多个类调用一个方法

转载 作者:行者123 更新时间:2023-11-30 06:24:48 25 4
gpt4 key购买 nike

编辑(16.05.2013):

我将使用我的第三个解决方案。感谢大家的帮助。

编辑结束 (16.05.2013)

我有一个带有更新方法的 View (在 Controller 内)。该方法必须由许多类调用。所以我想出了两个解决方案:

  1. 在每个需要调用更新方法的类中为 View / Controller 创建一个字段。
  2. 将更新方法设为静态。

什么是更好的 (M)VC 设计?如果两个或多个类同时调用更新方法会发生什么情况?

简化示例 1:

public class View{
public void update(){}
}

// Many classes:
public class AClass{
private View view;

private void aMethod(){
view.update();
}
}

简化示例 2:

public class View{
public static void update(){}
}

// Many classes:
public class AClass{

private void aMethod(){
View.update();
}
}

编辑(12.05.2013):我同意,“静态解决方案”不好,尤其是对于 OOP。

我稍微简化了一点,所以这是实际的设计:

假设您有一些 MVC 设计的程序,并希望将它们放在一个“大”程序中,但现在这些程序必须不时进行交互。

public class AView{
public void update(){}
}

public class AModel{}

//Many of these:
public class AController{
private AView aview;
private AModel amodel;

public AController(AView aview, AModel amodel){
this.aview=aview;
this.amodel=amodel;
}
}

public class MainController{
public MainController(){
AView view1 = new AView();
AModel model1 = new AModel();
AController controller1 = new AController(view1, model1);

AView view2 = new AView();
AModel model2 = new AModel();
AController controller2 = new AController(view2, model2);

AView view3 = new AView();
AModel model3 = new AModel();
AController controller3 = new AController(view3, model3);
}
}

现在假设controller1和controller2需要调用view3的update方法。我目前的解决方案是在 controller1 和 controller2 中创建一个视野 3(如您所建议的)。

AController controller1 = new AController(view1, view3, model1);
AController controller2 = new AController(view2, view3, model2);

或者我应该重构整个设计还是在 Controller 之间创建一个“桥梁”?那座“桥”会是什么样子?

编辑结束 (12.05.2013)

编辑 (14.05.2013):我想出了第三个解决方案:每个 Controller 都会触发它自己的事件。例如:

Controller1和Controller2触发事件,Controller3监听,然后调用View3的update方法。您如何看待这个解决方案?

编辑结束 (14.05.2013)

最佳答案

扔掉静态解决方案,甚至不要考虑这个,因为这样做你就把所有 OOP 都扔到了窗外。为控件提供一个公共(public) update() 方法,该方法在需要时调用 View 的方法。

话虽如此,但您的问题让我担心紧密耦合。

这些需要调用 View 更新的其他类——它们是控制类/库的一部分吗?只有控件应该在 View 上调用更新。


编辑,你说:

Could you please explain more on "Static method throw all OOP out of window" I am eager to learn that.

当你将方法设为静态时,它就不再是可继承的,更重要的是,它不再是类实例的方法,而是类对象的方法。因此,单独的实例将不再有自己独特的调用方法,它无法从实例获取状态数据,也无法更改实例的状态。

关于java - 良好的 MVC 设计,用于由多个类调用一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16502950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com