【问题标题】:Is it bad practice to use ActionListener(this)使用 ActionListener(this) 是不好的做法吗
【发布时间】:2013-08-09 15:51:31
【问题描述】:

在对我的一个答案的评论回复中,Hovercraft 说

不,您的建议确实会使事情变得更糟,因为通过将其用作 ActionListener,您是在建议他将他的 View 也设为 Control,这在“玩具”程序以外的任何东西中都不应该这样做。

作为一个新手,我一直在使用“this”,但我不清楚为什么如此不鼓励这样做。有人可以解释/详细说明气垫船的答案或给出另一个答案吗?

评论-- https://stackoverflow.com/questions/18021509/how-can-i-call-method-with-a-string/18021674#18021674

【问题讨论】:

  • 您可以链接到有问题的帖子或评论,而不是链接到用户?另外,也许您应该先尝试对他发表评论。
  • 听起来他是在建议分离关注点,而不是让你的班级处理比它必须做的更多的事情
  • 啊抱歉,我以为更多人也想知道,所以才问
  • this 在构造函数中:nat.truemesh.com/archives/000222.html 可能不好。
  • 这是参考了MVC的设计理念。你可以在这里阅读更多信息:en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

标签: java swing actionlistener


【解决方案1】:

这是因为 Swing 遵循MVC 模式。如果您将Controller 和View 委托给一个班级,那么就会出现问题。另请阅读Single Responsability Principle,一个班级只应该对一件事负责,如果不是,您的班级似乎就像一个God,可以做所有事情。

代替

public class MyJFrame extends JFrame implements KeyListener{
     MyJFrame(){
       this.addKeyListener(this); // sounds awful           
     }
}

使用这样的东西:

public class MyFrameView {

private JFrame frame;

     MyFrameView(){
       frame = new JFrame();
       frame.addKeyListener(new MyKeyListener());
     }

}

public class MyKeyListener implements KeyListener{

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-07
    • 2023-04-10
    • 2010-11-23
    • 1970-01-01
    • 2011-08-20
    • 2012-04-04
    • 1970-01-01
    相关资源
    最近更新 更多