建造者模式官方的概述:
代码语言:javascript复制 将一个复杂对象的构建与它的表示分离,
使得同样的构建过程可以创建不同的表示。
简单的说就是一个抽象的实体的构成,需要其部分组件的建造者一齐拼接而成。而我们调用者
直接装配这个抽象实体的创建者即可。
StringBuilder是最好的体现,你一直append,无所谓。。
uml如下
package org.huey.partten.builder;
抽象实体类,需要依赖多个组件
代码语言:javascript复制public class Company {
private Ceo ceo;
private Manager manager;
private Programmer programmer;
public void CompanyService(){
System.out.println("公司业务。。。。。");
}
public Ceo getCeo() {
return ceo;
}
public void setCeo(Ceo ceo) {
this.ceo = ceo;
}
public Manager getManager() {
return manager;
}
public void setManager(Manager manager) {
this.manager = manager;
}
public Programmer getProgrammer() {
return programmer;
}
public void setProgrammer(Programmer programmer) {
this.programmer = programmer;
}
}
//组件类
class Ceo {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Manager {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Programmer {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package org.huey.partten.builder;
/**
*
* 建造组件类
* @author huey
*
*
*/
public interface CompanyBuilder {
public Ceo buildCeo();
public Manager buildManager();
public Programmer buildProgrammer();
}
package org.huey.partten.builder;
public class CompanyBuilderImpl implements CompanyBuilder {
@Override
public Ceo buildCeo() {
System.out.println("need Ceo ..");
return new Ceo();
}
@Override
public Manager buildManager() {
System.out.println("need Manager ..");
return new Manager();
}
@Override
public Programmer buildProgrammer() {
System.out.println("need Programmer ..");
return new Programmer();
}
}
//装配类
package org.huey.partten.builder;
public interface CompanyDerector {
public Company buildCompany();
}
package org.huey.partten.builder;
public class CompanyDerectorImpl implements CompanyDerector {
private CompanyBuilder companyBuilder;
public CompanyDerectorImpl(CompanyBuilder companyBuilder) {
this.companyBuilder = companyBuilder;
}
@Override
public Company buildCompany() {
Ceo buildCeo = companyBuilder.buildCeo();
Manager buildManager = companyBuilder.buildManager();
Programmer buildProgrammer = companyBuilder.buildProgrammer();
Company company = new Company();
company.setCeo(buildCeo);
company.setManager(buildManager);
company.setProgrammer(buildProgrammer);
return company;
}
}
//测试类
package org.huey.partten.builder;
public class TestBuilder {
public static void main(String[] args) {
CompanyDerector companyDerector = new CompanyDerectorImpl(new CompanyBuilderImpl());
Company buildCompany = companyDerector.buildCompany();
System.out.println(buildCompany.getCeo());
buildCompany.CompanyService();
}
}
//测试结果
还是那句话,设计模式是一种思想,编程靠的就是思想。高级编程就是面向接口和抽象类编程。望读者有个概念,框架源码最为体现,公司封装的框架我虽然没接触过,但是我相信也是一个套路,毕竟它是结晶。谢谢对我们的支持!