有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

oop缩写长对象链(java)

首先,我想告诉大家,我最近开始使用java和面向对象编程,所以请原谅我这个愚蠢的问题,但我在其他地方找不到明确的答案

我正在为Comsol模型制作一个模板,我想缩写代码的一部分,使其更具可读性。尽管以下代码段与Comsol编译器一起运行:

Model model = ModelUtil.create("Model");    // Returns a model
model.geom().create("geom1");               // add a component
model.geom("geom1").create("circle")        // add a shape

//I would like to rewrite the following block of code:
model.geom("geom1").shape("circle").name("c1", "Circle");
model.geom("geom1").shape("circle").feature("c1").label("OuterDiameter");
model.geom("geom1").shape("circle").feature("c1").set("type", "curve");
model.geom("geom1").shape("circle").feature("c1").set("r", "0.5");

我想把model.geom("geom1").shape("circle")缩写成类似MGS的东西

我需要这样一个命令很多次,因为我还想用它来缩写model.material("mat1").propertyGroup("def")model.sol("sol1").feature("s1").feature("fc1")model.result("pg2").feature("iso1"),将来可能会更多

我更熟悉Python,它可以让我做一些非常简单的事情,比如:

MGS = model.geom("geom1").shape("circle")
MGS.name("c1", "Circle")
MGSF = MGS.feature("c1")
MGSF.label("OuterDiameter")
MGSF.set("type", "curve")

我在java中找不到任何类似的表达式

谢谢


共 (1) 个答案

  1. # 1 楼答案

    只需使用局部变量来存储重复访问的中间值。这不仅使代码更具可读性,而且在调用获取中间值的操作可能代价高昂的情况下提高了效率

    大致如下:

    Model model = ModelUtil.create("Model");    // Returns a model
    Geom g = model.geom();
    g.create("geom1");               // add a component
    Component c = model.geom("geom1");
    c.create("circle")                          
    
    Circle ci = c.shape("circle");
    ci.name("c1", "Circle");
    Feature f = ci.feature("c1");
    f.label("OuterDiameter");
    f.set("type", "curve");
    f.set("r", "0.5");
    

    请注意,这只是一个定向示例,不打算仅通过复制&;粘贴。GeomComponentFeatureCircle类可能与方法的实际类名或实际返回类型不对应,我不知道您的代码所使用的API的细节