在类构造函数的参数巨额优雅的替代品 [英] Elegant alternatives for huge amount of arguments in class constructor

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

问题描述

例如我有一个类,构建GUI,处理的图形用户界面,并且认为通过GUI对象(主要是滑条)和实例都GUI所有受影响的对象主类中的所有事件类级和事件级。

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天全站免登陆