建造者模式详解
Posted sharkchao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了建造者模式详解相关的知识,希望对你有一定的参考价值。
定义:将一个复杂的构建与他的表示分离,使得同样的构建过程可以创建不同的表示.
public class Computer { private String cpu; private String mainBoard; private String ram; public String getCpu() { return cpu; } public void setCpu(String cpu) { this.cpu = cpu; } public String getMainBoard() { return mainBoard; } public void setMainBoard(String mainBoard) { this.mainBoard = mainBoard; } public String getRam() { return ram; } public void setRam(String ram) { this.ram = ram; } public static class Builder{ private String cpu; private String mainBoard; private String ram; public String getCpu() { return cpu; } public Builder setCpu(String cpu) { this.cpu = cpu; return this; } public String getMainBoard() { return mainBoard; } public Builder setMainBoard(String mainBoard) { this.mainBoard = mainBoard; return this; } public String getRam() { return ram; } public Builder setRam(String ram) { this.ram = ram; return this; } public Computer create(){ Computer computer = new Computer(); computer.setRam(ram); computer.setMainBoard(mainBoard); computer.setCpu(cpu); return computer; } } }
将computer的构建都放在builder中去构建。
Test:
public class Test { public static void main(String[]args){ Computer computer = new Computer.Builder() .setCpu("cpu") .setMainBoard("mainborad") .setRam("ram") .create(); } }
以上是关于建造者模式详解的主要内容,如果未能解决你的问题,请参考以下文章