设计模式 -> 构建者模式Builder

版权声明: https://blog.csdn.net/bsfz_2018/article/details/83212264

在swagger,shiro等源码中构建者模式使用非常普及,以例子驱动

package test;

/**
 * 构建者模式
 *
 * 避免getter,setter代码冗杂
 * 避免参数条件配置数量导致的含参构造代码冗杂
 * @author Nfen.Z
 */
public class Post {

    private int id;
    private String title;
    private String content;
    private String author;

    public Post(Builder builder) {
        this.id = builder.id;
        this.title = builder.title;
        this.content = builder.content;
        this.author = builder.author;
    }

    @Override
    public String toString() {
        return "Post{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                ", author='" + author + '\'' +
                '}';
    }

    // 只要内部类key被声明为静态,此处声明为静态仅仅为了通过 A.B方式来调用
    static class Builder {

        private int id;
        private String title;
        private String content;
        private String author;

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

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

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

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

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

    }

    public static void main(String[] args) {
        Post test = new Post.Builder().id(2).content("测试").build();
        System.out.println(test);
    }

}

结果如下:
在这里插入图片描述

静态内部类和非静态内部类区别

  • 静态内部类只能够访问外部类的静态成员,而非静态内部类则可以访问外部类的所有成员(方法,属性)
  • 静态内部类和非静态内部类在创建时有区别

//假设类A有静态内部类B和非静态内部类C,创建B和C的区别为:

A a=new A(); 
A.B b=new A.B(); 
A.C c=a.new C();

猜你喜欢

转载自blog.csdn.net/bsfz_2018/article/details/83212264