Java如何使用Build模式构造对象呢?

戚薇 Java经验 发布时间:2023-06-23 22:46:47 阅读数:18316 1
下文笔者讲述Java代码使用Build模式构造对象的方法及示例分享
学习完本篇你将掌握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);
	}
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202306/16875316536869.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者