类构造函数中大量参数的优雅替代方案 [英] Elegant alternatives for huge amount of arguments in class constructor

查看:27
本文介绍了类构造函数中大量参数的优雅替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个构建 GUI 的类,一个处理 GUI 的所有事件的类和包含受 GUI 对象(主要是滑块)影响的所有对象的主类以及 GUI 实例-class 和 event-class.

For example I have a class that builds the GUI, a class that handles all the events for the GUI and the main class that holds all the objects that are affected by the GUI-Objects (mostly sliders) and instances both the GUI-class and event-class.

现在事件类的构造函数将 GUI 类和每个正在被 GUI 更改的对象作为参数.这些对象非常多,所以我现在拥有的参数数量大约是 8 个,而且还在增加.

Now the event-class's constructor has as arguments the GUI class and every object that is being changed by the GUI. These are quite allot of objects so the amount of arguments I have now are about 8 and still growing.

是否有更优雅的解决方案来解决我的问题,30 个参数根本感觉不对?

Is there a more elegant solution to my problem, 30 arguments simply doesn't feel right?

ps,我宁愿不合并类,因为这三个类都很大,而且会使所有内容的可读性大大降低.

ps, I'd rather not combine classes because all three are quite big and would make everything much less readable.

推荐答案

您可以创建一个配置类来保存所有参数的默认值:

You can create a configuration class which holds default values for all parameters:

public class GUIConfig {

  private String name = "default";
  // more private declarations

  public GUIConfig() {
    // constructor, just for setting defaults
  }

  // getters and setters

}

现在您可以像这样简单地创建您的 GUI 类实例:

Now you can simply create your GUI class instance like this:

GUIConfig guiConfig = new GUIConfig();
guiConfig.setName("foo");
// more setters
GUI myGUI = new GUI(guiConfig);

或仅使用默认值:

GUI myGUI = new GUI(new GUIConfig());

这篇关于类构造函数中大量参数的优雅替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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