搜索模式 - 填充模型

时间:2016-01-28 14:48:13

标签: java design-patterns

我正在编写一个java应用程序,我必须用值填充普通对象。

示例对象

public class A {
    private String a;

    private String b;

    // ...

    public String getB() {
        return b;
    }

    public void setB(String b) {
        this.b = b;
    }

    public String getA() {
        return a;
    }

    public void setA(String a) {
        this.a = a;
    }

    // ...
}

我这样填写

public class Initalizer {
    public A init()  {
        A a = new A();

        a.setA(// get it from somewhere
        );
        a.setB(// get it from somewhere
        );
        // ...

        return a;
    }
}

在这种情况下,我从jsoup获取值,一个html-parser

我的问题是: 有更优雅的方式吗?比如定义一个填充一个属性的方法。就像在乐高中,一块石头适合另一块石头。

有一种我不知道的设计模式吗?

感谢您的帮助

3 个答案:

答案 0 :(得分:0)

是的,有许多符合您需求的设计模式。这些模式称为 Creational Patterns ,如:

工厂模式:

  

工厂模式是Java中最常用的设计模式之一。这个类型   设计模式作为这种模式在创作模式下   提供了创建对象的最佳方法之一。

对于更复杂的对象构建,还有构建器模式

  

Builder模型使用简单对象和使用构建复杂对象   一步一步的方法。这种设计模式来自于此   创作模式,因为这种模式提供了最好的方法之一   创建一个对象。

您可以通过示例找到更多here

答案 1 :(得分:0)

有一种名为Builder Pattern的模式可以帮助您链接构建对象的方法。

public class A {
    private String a;

    private String b;

    // ...

    public String getB() {
        return b;
    }

    public A setB(String b) {
        this.b = b;
        return this;
    }

    public String getA() {
        return a;
    }

    public A setA(String a) {
        this.a = a;
        return this;
    }

    // ...
}

你可以像这样使用它:

public class Initalizer {
    public A init()  {
        return new A().setA(...).setB(...);
    }
}

答案 2 :(得分:0)

我建议的是建筑师模式方法。它对你的一点点修改。这是一个非常好的资源,可以更深入地了解这种模式here

public class A {
    private final String a;
    private final String b;

    public static class builder {
        private String a;
        private String b;

        public Builder a(String a) {
            this.a = a;
            return this
        }

        public Builder b(String a) {
            this.b = b;
            return this
        }

        public A build() {
            return new A(this);
        }
    }
      private A(Builder builder){
          this.a = builder.a;
          this.b = builder.b;
   }
}

您将以这种方式初始化您的课程;

A a = new A.Builder()
           .a("string")
           .b("string")
           .build();
相关问题