設計模式 Builder模式

2021-08-20 21:55:28 字數 3011 閱讀 9628

public

class person

public

void

setname(string name)

public

intgetage()

public

void

setage(int age)

public

double

getheight()

public

void

setheight(double height)

public

double

getweight()

public

void

setweight(double weight)

}

public

person(string name, int age, double height, double weight)

public

person()

public

person(string name)

public

person(string name, int age)

public

person(string name, int age, double height)

person p1=new person();

person p2=new person("張三");

person p3=new person("李四",18);

person p4=new person("王五",21,180);

person p5=new person("趙六",17,170,65.4);

public

class person

public string getname()

public

void

setname(string name)

public

intgetage()

public

void

setage(int age)

public

double

getheight()

public

void

setheight(double height)

public

double

getweight()

public

void

setweight(double weight)

static class builder

public builder age(int age)

public builder height(double height)

public builder weight(double weight)

public person build()

}}

person.builder builder=new person.builder();

person person=builder

.name("張三")

.age(18)

.height(178.5)

.weight(67.4)

.build();

alertdialog.builder builder=new alertdialog.builder(this);

alertdialog dialog=builder.settitle("標題")

.seticon(android.r

.drawable

.ic_dialog_alert)

.setview(r.layout

.myview)

.setpositivebutton(r.string

.positive, new dialoginte***ce.onclicklistener()

}).setnegativebutton(r.string

.negative, new dialoginte***ce.onclicklistener()

}).create();

dialog.show();

gsonbuilder builder=new gsonbuilder();

gson gson=builder.setprettyprinting()

.disablehtmlescaping()

.generatenonexecutablejson()

.serializenulls()

.create();

public

static eventbusbuilder builder()

public

eventbus()

eventbus(eventbusbuilder builder)

request.builder builder=new request.builder();

request request=builder.addheader("","")

.url("")

.post(body)

.build();

private response(builder builder)
builder類通過一系列的方法用於成員變數的賦值,並返回當前物件本身(this)

builder類提供乙個build方法或者create方法用於建立對應的外部類,該方法內部呼叫了外部類的乙個私有建構函式,該建構函式的引數就是內部類builder

外部類提供乙個私有建構函式供內部類呼叫,在該建構函式中完成成員變數的賦值,取值為builder物件中對應的值

設計模式 Builder模式

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

設計模式 Builder模式

網路上有人將它定義為 將乙個複雜物件的構建與它的表示分離,使得同樣的構建過程可以建立不同的物件。所以建造者模式適合於乙個具有較多的零件 屬性 的產品 物件 的建立過程。由五個部分構成 1.product concreatebuilder建立該產品的內部表示並定義它的裝配過程。2.builder介面 ...

設計模式 Builder模式

一貫風格,直接上 package created by mingchenchen on 2017 6 14.public class user public void setid string id public string getcountry public void setcountry st...