Builder設計模式結合lombok減少過多傳參

2021-09-07 05:09:35 字數 2678 閱讀 9065

建造者模式將複雜物件的建立過程簡化,用來傳參也很合適。lombok的主要作用是通過一些註解,消除樣板式**,更多詳見 lombok官網。該框架已經內建了這種模式。

過多的傳參,可讀性差,尤其是引數型別一致順序還容易寫顛倒。下面以一則不友好的傳參為例展示一下,如何通過lombok迅速重構。

public class mytest 

public static void pay(string date, string name, string term, string amount)

}

首先將引數封裝。 

builder跟date分別是兩個聚合註解,省去了手寫getter、setter跟builder方法。

import lombok.builder;

import lombok.data;

@data

@builder

public class bidbuilder

加上該註解後,通過反編譯發現lombok生成的實際**如下

public class bidbuilder

public void setname(string name)

public void setterm(string term)

public void setamount(string amount)

public boolean equals(object o)

if (!(o instanceof bidbuilder))

bidbuilder other = (bidbuilder)o;

if (!other.canequal(this))

object this$date = getdate();object other$date = other.getdate();

if (this$date == null ? other$date != null : !this$date.equals(other$date))

object this$name = getname();object other$name = other.getname();

if (this$name == null ? other$name != null : !this$name.equals(other$name))

object this$term = getterm();object other$term = other.getterm();

if (this$term == null ? other$term != null : !this$term.equals(other$term))

object this$amount = getamount();object other$amount = other.getamount();return this$amount == null ? other$amount == null : this$amount.equals(other$amount);

} protected boolean canequal(object other)

public int hashcode()

public string tostring()

public static class bidbuilderbuilder

public bidbuilder build()

public bidbuilderbuilder amount(string amount)

public bidbuilderbuilder term(string term)

public bidbuilderbuilder name(string name)

public bidbuilderbuilder date(string date)

} bidbuilder(string date, string name, string term, string amount)

public static bidbuilder.bidbuilderbuilder builder()

public string getdate()

public string getname()

public string getterm()

public string getamount()

}

通過lombok幾行**就實現了大量需要手動完成的模版**。重構後如下

public class mytest2 

public static void pay(bidbuilder bidbuilder)

}

後續若需要新增新的引數,只需更改bidbuilder,比如新增下次還款時間,只需要新增一行.

@data

@builder

public class bidbuilder

// 然後動態生成新的builder

bidbuilder bidbuilder =

bidbuilder.builder()

.date("2018-02-25")

.name("小明")

.term("2")

.amount("100")

.nextdate("2018-03-25")

.build();

Builder設計模式

builder設計模式一般會採用鏈式程式設計結構 案例分析?構建一台電腦 記憶體 cpu 顯示卡等等 記憶體 r am 執行記憶體 和 rom 非執行記憶體 分為了一些角色 builder 抽象類 規範產品組裝 案例中builder介面 concratebuilder 具體組裝產品類 案例macbo...

Builder設計模式

當乙個類需要過載多個構造方法時,並且引數隨機使用時,builder模式就出現了。官方說法 將乙個複雜的物件的構建與他的表示相分離,使用者可以一步一步構建乙個比較複雜的物件。自己理解 先通過某種方式取得構造物件所需要的所有引數,再通過這些引數一次性構建這個物件。實現如下 package com.dem...

設計模式 Builder模式

bulder模式是一步步建立乙個複雜物件的建立模型,它允許使用者在不知道內部構建細節 的情況下可以更精細地控制物件的構造流程該模式為將構建複雜物件的過程和它的部件 解耦,使得構建過程和部件的表示隔離開來。將乙個負責物件的構建與它的表示分離,使得同樣的構建過程可以建立不同的表示 3.1 相同的方法,不...