本篇内容主要讲解“step-builder建造者模式是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“step-builder建造者模式是什么”吧!
step-builder 建造者模式是链式建造者模式的近一步扩展, 能够按步骤实例化对象.
还是以建造一个Compute为例,代码如下↓↓↓
public class Computer { private String cpu; private String ram; private String screen; public String getCpu() { return cpu; } public void setCpu(String cpu) { this.cpu = cpu; } public String getRam() { return ram; } public void setRam(String ram) { this.ram = ram; } public String getScreen() { return screen; } public void setScreen(String screen) { this.screen = screen; } }
public class ComputerBuilder { private ComputerBuilder() {} public static CpuStep getBuilder(){ return new ComputerSteps(); } interface CpuStep{ RamStep withCpu(String cpu); } interface RamStep{ ScreenStep withRam(String ram); } interface ScreenStep{ BuildStep withScreen(String screen); } interface BuildStep{ Computer build(); } public static class ComputerSteps implements CpuStep,RamStep,ScreenStep,BuildStep{ private Computer computer; public ComputerSteps() { this.computer = new Computer(); } @Override public RamStep withCpu(String cpu) { this.computer.setCpu(cpu); return this; } @Override public ScreenStep withRam(String ram) { this.computer.setRam(ram); return this; } @Override public BuildStep withScreen(String screen) { this.computer.setScreen(screen); return this; } @Override public Computer build() { return this.computer; } } }
public static void main(String[] args) { Computer computer = ComputerBuilder.getBuilder().withCpu("cpu型号").withRam("ram型号").withScreen("屏幕型号").build(); }
将每一步抽象为一个接口, 完成第一步后返回的是下一步的接口,以此保证只能按照接口顺序执行.
到此,相信大家对“step-builder建造者模式是什么”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。