这篇文章主要介绍“如何使用传统建造者模式”,在日常操作中,相信很多人在如何使用传统建造者模式问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”如何使用传统建造者模式”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
传统建造者模式 由四种角色组成 1.产品类 2.建造者抽象类 3.建造者类 4.Director指挥者角色.
Builder知道怎么建造一个对象, Director可以自由发挥,指挥builder完成不同部件的建造.
链式建造者模式,是传统建造者模式的简化.
public class Computer { private String cpu; private String ram; 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; } @Override public String toString() { return "Computer{" + "cpu='" + cpu + '\'' + ", ram='" + ram + '\'' + '}'; } }
public interface Builder { void buildCpu(); void buildRam(); Computer getComputer(); }
public class LenovoBuilder implements Builder { private Computer computer; public LenovoBuilder() { computer = new Computer(); } @Override public void buildCpu() { computer.setCpu("联想cpu"); } @Override public void buildRam() { computer.setRam("联想ram"); } @Override public Computer getComputer() { return computer; } }
public class AppleBuilder implements Builder{ private Computer computer; public AppleBuilder() { computer = new Computer(); } @Override public void buildCpu() { computer.setCpu("苹果cpu"); } @Override public void buildRam() { computer.setRam("苹果ram"); } @Override public Computer getComputer() { return computer; } }
public class Director { public Computer buildAComputer(Builder builder){ builder.buildRam(); builder.buildCpu(); return builder.getComputer(); } }
public static void main(String[] args) { Director director = new Director(); LenovoBuilder lenovoBuilder = new LenovoBuilder(); AppleBuilder appleBuilder = new AppleBuilder(); Computer lenovoComputer = director.buildAComputer(lenovoBuilder); Computer appleComputer = director.buildAComputer(appleBuilder); System.out.println(lenovoComputer); System.out.println(appleComputer); }
到此,关于“如何使用传统建造者模式”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。