[Spring Pattern] Builder pattern

First, let's see the code:

复制代码
// builder/Contact.java

public class Contact {
    private String firstName;
    private String lastName;
    private String emailAddress;

    public Contact() {
        super()
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(final String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(final String lastName) {
        this.lastName = lastName;
    }

    public String getEmailAddress() {
        return emailAddress;
    }

    public void setEmailAddress(final String emailAddress) {
        this.emailAddress = emailAddress;
    }
}
复制代码

 

Using it:

复制代码
    @GetMapping("presidents")
    public List<Contact> getPresidents() {
        List<Contact> contacts = new ArrayList<>();

        Contact contact = new Contact();
        contact.setFirstName("George");
        contact.setLastName("Washington");
        contacts.add(contact);

        contacts.add(new Contact("John", "Adams", null));

        return contacts;
    }
复制代码

For the highlighted part, there are two ways to create contact object.

One is multi lines:

        Contact contact = new Contact();
        contact.setFirstName("George");
        contact.setLastName("Washington");
        contacts.add(contact);

Another way is single line:

contacts.add(new Contact("John", "Adams", null));

 

The problems are 1. too much line of code when object get complex; 2. The order of params you need to rememeber.

 

Builder pattern:

复制代码
public class ContactBuilder {
    private String firstName;
    private String lastName;
    private String emailAddress;

    public ContactBuilder setFirstName(final String firstName) {
        this.firstName = firstName;
        return this;
    }

    public ContactBuilder setLastName(final String lastName) {
        this.lastName = lastName;
        return this;
    }

    public ContactBuilder setEmailAddress(final String emailAddress) {
        this.emailAddress = emailAddress;
        return this;
    }

    public Contact buildContact () {
        return new Contact(firstName, lastName, emailAddress);
    }
}
复制代码

Keep returning 'this' to enable chaining method calls. 

 

Using it:

复制代码
    @GetMapping("presidents")
    public List<Contact> getPresidents() {
        List<Contact> contacts = new ArrayList<>();

        Contact contact = new Contact();
        contact.setFirstName("George");
        contact.setLastName("Washington");
        contacts.add(contact);

        contacts.add(new Contact("John", "Adams", null));

        // using ContactBuilder
        contacts.add(
                new ContactBuilder()
                        .setFirstName("Thomas")
                        .setLastName("Jefferson")
                        .buildContact()
        )
        return contacts;
    }
复制代码

 

When to use this pattern:

1. Useful when object creation has many parameters

2. Becomes increasingly more useful when some or all parameters are optional

3. Can make code easier to read because of reduced lines for construction when compared with setters

 

posted @   Zhentiw  阅读(88)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-11-13 [Javascript] Check Promise is Promise
2019-11-13 [Javascript] Use requestIdleCallback to schedule JavaScript tasks at an optimal time
2019-11-13 [Javascript] Convert a callback based async operation into a Promise based
2017-11-13 [Python] String Formatting
2017-11-13 [TypeScript] Shallow copy object by using spread opreator
2017-11-13 [TypeScript] Model Alternatives with Discriminated Union Types in TypeScript
2015-11-13 [WebStrom] Change default cmd to Cygwin
点击右上角即可分享
微信分享提示