設計模式 -> 構建者模式Builder
阿新 • • 發佈:2018-12-16
在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();