參考自:https://www.jianshu.com/p/afe090b2e19c設計模式
建造者模式是平常開發中比較常見的設計模式,它的主要做用就是將復瑣事物建立的過程抽象出來,該抽象的不一樣實現方式不一樣,建立出的對象也不一樣。通俗的講,建立一個對象通常都會有一個固定的步驟,這個固定的步驟咱們把它抽象出來,每一個抽象步驟都會有不一樣的實現方式,不一樣的實現方式建立出的對象也將不一樣。舉個常見的例子,想必你們都知道坦克大戰這種小遊戲,選擇不一樣的模式有不一樣的地圖(默認簡單版的,複雜版的),咱們選擇簡單版,那麼構建出來的地圖當中可能沒有碉堡,地雷等等,選擇複雜的版本可能就包含了這些東西,咱們能夠把這個地圖的構建步驟抽象出來,根據不一樣的版本構建不一樣的內容。ide
若是一個類有多個構造函數,通常超過4個都算多了,且有些參數是可選的,咱們就應該考慮用建造者模式來構建這個類的對象函數
從上圖能夠看到,Buider模式中有三個角色:ui
接下來咱們來看下用代碼如何實現上述地圖構建的過程:this
public class Terrain { Wall w; Fort f; Mine m; } class Wall { int x, y, w, h; public Wall(int x, int y, int w, int h) { this.x = x; this.y = y; this.w = w; this.h = h; } } class Fort { int x, y, w, h; public Fort(int x, int y, int w, int h) { this.x = x; this.y = y; this.w = w; this.h = h; } } class Mine { int x, y, w, h; public Mine(int x, int y, int w, int h) { this.x = x; this.y = y; this.w = w; this.h = h; } }
package com.mashibing.Builder; public interface TerrainBuilder { TerrainBuilder buildWall(); TerrainBuilder buildFort(); TerrainBuilder buildMine(); Terrain build(); }
這個具體的構建過程能夠有多個實現,好比遊戲能夠根據不一樣的模式構建多個不一樣的地圖(簡單版,經典版,複雜版。。。)spa
package com.mashibing.Builder; public class ComplexTerrainBuilder implements TerrainBuilder{ Terrain terrain = new Terrain(); @Override public TerrainBuilder buildWall() { terrain.w = new Wall(10,10,50,50); return this; } @Override public TerrainBuilder buildFort() { terrain.f = new Fort(10,10,50,50); return this; } @Override public TerrainBuilder buildMine() { terrain.m = new Mine(10,10,50,50); return this; } @Override public Terrain build() { return terrain; } }
package com.mashibing.Builder; public class Main { public static void main(String[] args) { TerrainBuilder builder = new ComplexTerrainBuilder(); Terrain t = builder.buildFort().buildWall().buildMine().build(); } }
package com.mashibing.Builder; public class Person { private int id; private String name; private int age; private double weight; private int score; private Location loc; private Person() {} public static class PersonBuilder{ Person p = new Person(); public PersonBuilder basicInfo(int id,String name,int age){ p.id = id; p.name = name; p.age = age; return this; } public PersonBuilder weight(double weight){ p.weight = weight; return this; } public PersonBuilder score(int score){ p.score = score; return this; } public PersonBuilder loc(String street,String roomNo){ p.loc = new Location(street, roomNo); return this; } public Person build(){return p;} } } class Location{ String street; String roomNo; public Location(String street, String roomNo) { this.street = street; this.roomNo = roomNo; } }
package com.mashibing.Builder; public class Main { public static void main(String[] args) { Person p = new Person.PersonBuilder().basicInfo(1,"zhangsan",18) .score(20) .weight(128.2) .loc("a","a").build(); } }