Java如何使用Build模式构造对象呢?
下文笔者讲述Java代码使用Build模式构造对象的方法及示例分享
学习完本篇你将掌握Builder模式的基本使用方法,如下所示
学习完本篇你将掌握Builder模式的基本使用方法,如下所示
1.定义静态方法,返回对象 2.每一个对象的set方法都直接返回对象 使用build模式构造对象 可实现当多个参数后 连续赋值的效果例:Build模式构造对象的示例
package testBuildObj; public class TestBuildObject { private int id; private String name; private String address; private TestBuildObject(int id, String name, String address) { super(); this.id = id; this.name = name; this.address = address; } public static MyBuilder newBuilder() { return new MyBuilder(); } public static class MyBuilder{ private int id; private String name; private String address; public MyBuilder id(int id) { this.id = id; return this; } public MyBuilder name(String name) { this.name = name; return this; } public MyBuilder address(String address) { this.address = address; return this; } public TestBuildObject build() { TestBuildObject obj = new TestBuildObject(this.id, this.name, this.address); return obj; } } public int getId() { return id; } public String getName() { return name; } public String getAddress() { return address; } @Override public String toString() { return "TestBuildObject [id=" + id + ", name=" + name + ", address=" + address + "]"; } } //测试示例 package testBuildObj; public class TestBuildObjMain { public static void main(String[] args) { TestBuildObject obj = TestBuildObject.newBuilder().id(12).name("Tom").address("Pandora").build(); System.out.println(obj); TestBuildObject obj2 = TestBuildObject.newBuilder().name("Jerry").build(); System.out.println(obj2); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。