软件架构 - 改变全局变量 class

Software Architecture - Changing variables in global class

我有时对如何更新 "global class" 中的变量感到困惑。例如,我有 Software class 显示包裹在 UI 组件中的状态字符串,StateHandler 更新 states/status,Plugin class 单击按钮时更新状态。一个类似于 Java 的伪代码可能大致是:

class Software{
    JLabel state;
    ...
    void CreateUI(){
        ...
        state = new JLabel(defaultState);
        window.add(state);
    }
}

class StateHandler{
    static String stateString;
    public void updateStateString(){...}
}

class Plugin{
    ...

    JButton button;
    void initButton(){
        button.addListener(new EventListener(){
            //update state here
        });
    }
}

如果我在 Software class 中将 JLabel 设置为静态,它将跨软件的不同实例更新状态。如果我将 JLabel 放在 StateHandler 中,我无法找到一种方法来初始化组件并将其添加到 Software class 中的 UI 中。 StateHandler.state = new JLabel(); returns 一个错误。

当然,一种替代方法是将软件的引用传递给 Plugin 实例,然后执行一些操作 software.updateState(); 但这不是很聪明。

执行此操作的最佳做​​法是什么?谢谢。

不确定我的目的是否正确,但由于 Software 拥有该标签,我建议它还提供一个事件方法来更新它...

那么你能完全摆脱 StateHandler 吗?因为那样你就可以将标签的处理封装在软件里面。

所以在软件中,假设您添加方法

public static void updateState() {...}

然后完全跳过 StateHandler,当你初始化你的按钮时,你可以利用 Java 中的 EventHandler 构建器(假设 updateState() 确实是一个没有参数的方法)在这种情况下你会做一些事情在插件中像这样:

button.addActionListener(
(ActionListener)EventHandler.create(ActionListener.class,  
 softwareInstance, "updateState"));

基于以下评论的备选建议。创建接口来表示插件类型,并允许主框架在初始化时加载它的插件。使用一些类似伪代码的简短示例:

创建接口,例如:

public interface IStatePlugin {
String UpdateState();
JButton GetControl();
}

其中 GetControl() returns 按钮。如果它们在插件列表中,这允许加载多个状态控制器和按钮。

然后在主框架 init 中执行类似的操作(通过已找到和激活的插件列表):

//Here we would accept a more general interface in reality, such as IPlugin

public static void InitMain(final MainFrame f, final TestPlugin p) {

//Check what plugin we loaded, in reality this would be a list of different types, marked by their marker iface
if(p instanceof IStatePlugin) {
        //It's a state plugin, so hook it up... 
        JButton b = p.GetControl();
        //Assume since it is an IStatePlugin marker, that it has method UpdateState, add the event
       b.addActionListener(new ActionListener() {
           @Override
            public void actionPerformed(ActionEvent e) {
                f.lblTest.setText(p.UpdateState());
            }    
        });

        //Add the button    
        f.btnPanel.add(b);
        f.btnPanel.validate();

        //...
    } 
}

插件class可以定义为软件class的内部class和按钮操作它可以更新相应的软件状态外部实例