1. 建造者(Builder)模式
创建的东西细节复杂,还必须暴露给使用者。屏蔽过程而不屏蔽细节
产品角色(Product):Phone
/**
* 只暴露get方法 不暴露set方法
*/
public class Phone {
protected String cpu;
protected String mem;
protected String disk;
protected String cam;
public String getCpu() {
return cpu;
}
public String getMem() {
return mem;
}
public String getDisk() {
return disk;
}
public String getCam() {
return cam;
}
@Override
public String toString() {
return "Phone{" +
"cpu='" + cpu + '\'' +
", mem='" + mem + '\'' +
", disk='" + disk + '\'' +
", cam='" + cam + '\'' +
'}';
}
}
抽象建造者(Builder):AbstracPhoneBuilder
public abstract class AbstractBuilder {
Phone phone;
abstract void customCpu(String cpu);
abstract void customMem(String mem);
abstract void customDisk(String disk);
abstract void customCam(String cam);
Phone getProduct() {
return phone;
}
}
具体建造者(Concrete Builder):PhoneBuilder
public class XiaomiBuilder extends AbstractBuilder {
public XiaomiBuilder() {
phone = new Phone();
}
@Override
void customCpu(String cpu) {
phone.cpu = cpu;
}
@Override
void customMem(String mem) {
phone.mem = mem;
}
@Override
void customDisk(String disk) {
phone.disk = disk;
}
@Override
void customCam(String cam) {
phone.cam = cam;
}
}
测试方法:
public static void main(String[] args) {
AbstractBuilder builder = new XiaomiBuilder();
builder.customCpu("骁龙888");
builder.customCam("一亿");
builder.customDisk("512G");
builder.customMem("12G");
}
在建造者模式中常用的链式我们也可以实现,只需将设置属性方法返回自身即可。
抽象建造者:
public abstract class AbstractBuilder2 {
Phone phone;
abstract AbstractBuilder2 customCpu(String cpu);
abstract AbstractBuilder2 customMem(String mem);
abstract AbstractBuilder2 customDisk(String disk);
abstract AbstractBuilder2 customCam(String cam);
Phone getProduct() {
return phone;
}
}
具体建造者:
public class XiaomiBuilder2 extends AbstractBuilder2 {
public XiaomiBuilder2() {
phone = new Phone();
}
@Override
AbstractBuilder2 customCpu(String cpu) {
phone.cpu = cpu;
return this;
}
@Override
AbstractBuilder2 customMem(String mem) {
phone.mem = mem;
return this;
}
@Override
AbstractBuilder2 customDisk(String disk) {
phone.disk = disk;
return this;
}
@Override
AbstractBuilder2 customCam(String cam) {
phone.cam = cam;
return this;
}
}
测试方法:
public static void main(String[] args) {
//链式调用
AbstractBuilder2 builder2 = new XiaomiBuilder2();
Phone phone2 = builder2.customCpu("天玑9000").customCam("6400万").customMem("12G")
.customDisk("512G").getProduct();
System.out.println(phone2);
}
2. 应用场景
- StringBuilder:append(); 给谁append呢?
- Swagger-ApiBuilder:
- 快速实现。Lombok-Builder模式
编写代码的时候使用到了设计模式。类+模式
- xxxFactory
- xxxTemplate
- xxxBuilder
- xxxFacede