本文主要是介绍建造者模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
电脑用cpu,gpu,memory,hardDisk,power
public class Computer {
private String cpu;
private String gpu;
private String memory;
private String hardDisk;
private String power;
//省略getset和tostring
}
public interface ComputerBuilder {
public void cpu();
public void gpu();
public void memory();
public void hardDisk();
public void power();
public Computer build();
}
public class Director {
public Computer build(ComputerBuilder builder) {
builder.cpu();
builder.gpu();
builder.memory();
builder.hardDisk();
builder.power();
return builder.build();
}
}
public class PickComputer1 implements ComputerBuilder{
private Computer computer = new Computer();
@Override
public void cpu() {
computer.setCpu("cpu1");
}
@Override
public void gpu() {
computer.setGpu("gpu1");
}
@Override
public void memory() {
computer.setMemory("memory1");
}
@Override
public void hardDisk() {
computer.setHardDisk("hardDisk1");
}
@Override
public void power() {
computer.setPower("power1");
}
@Override
public Computer build() {
return computer;
}
}
public class Customer {
public static void main(String[] args) {
Director d = new Director();
Computer computer = d.build(new PickComputer1());
System.out.println(computer);
}
}
这篇关于建造者模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!