且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用“旧”的“生成器”模式创建新对象对象引用

更新时间:2021-12-29 08:22:20

让Builder构造函数以旧对象为参数,并设置任何你想从它到新的。

Make the Builder constructor take as an argument the "old" object and set whatever you want from it to the new one.

编辑

您需要阅读更多关于构建器模式的信息更好地掌握它是什么,如果你真的需要它。

You need to read a bit more about the builder pattern to get a better grasp at what it is and if you really need it.

一般的想法是,当你有可选元素。有效的Java项目2是您***的朋友。

The general idea is that Builder pattern is used when you have optional elements. Effective Java Item 2 is your best friend here.

对于您的类,如果要从另一个构建一个对象并同时使用Builder模式, / p>

For your class, if you want to build one object from another and use a Builder pattern at the same time, you


  1. 在Builder构造函数中传递旧对象

  2. 创建一个方法 fromOld 等。

  1. Either pass the "old" object in the Builder constructor
  2. Create a method from or fromOld, etc.

那么这样看起来如何?我将只提供第一个你可以自己找出第二个。

So how does that looks like? I am going to provide only the first one you can figure out the second on your own.

class MsProjectTaskData {
    private final String firstname;
    private final String lastname;
    private final int age;

    private MsProjectTaskData(Builder builder){
        this.firstname = builder.firstname;
        this.lastname  = builder.lastname;
        this.age       = builder.age;
    }

    public static final class Builder{
        //fields that are REQUIRED must be private final
        private final String firstname;
        private final String lastname;

        //fields that are optional are not final
        private int age;

        public Builder(String firstname, String lastname){
            this.firstname = firstname;
            this.lastname  = lastname;
        }

        public Builder(MsProjectTaskData data){
            this.firstname = data.firstname; 
            this.lastname  = data.lastname;
        }

        public Builder age(int val){
            this.age = val; return this;
        }

        public MsProjectTaskData build(){
            return new MsProjectTaskData(this);
        }
    }

    public String getFirstname() {
         return firstname;
    }

    public String getLastname() {
         return lastname;
    }

    public int getAge() {
         return age;
    }
}

您将如何从另一个创建一个对象: / p>

And how you will create one object from another:

   MsProjectTaskData.Builder builder = new MsProjectTaskData.Builder("Bob", "Smith");
   MsProjectTaskData oldObj = builder.age(23).build();
   MsProjectTaskData.Builder newBuilder = new MsProjectTaskData.Builder(oldObj);
   MsProjectTaskData newObj = newBuilder.age(57).build();
   System.out.println(newObj.getFirstname() + " " + newObj.getLastname() + " " + newObj.getAge()); // Bob Smith 57