一般我们会以这种设计方式生产对象实例,如:
创建一个接口:
public interface TestOpen { String getVirtualHost(); String getCapabilities(); boolean getInsist(); }
实现该接口:
public class TestOpenImpl implements TestOpen { private String t1; private String t2; private String t3; public TestOpenImpl() { } public TestOpenImpl(String t1,String t2,String t3) { //doSomething... } @Override public String getVirtualHost() { return null; } @Override public String getCapabilities() { return null; } @Override public boolean getInsist() { return false; } }
创建一个构造器:
public class TestOpenBuilder { public static TestOpen Build() { return new TestOpenImpl(); } public static TestOpen Build(String t1,String t2,String t3) { return new TestOpenImpl(t1,t2,t3); } }
所以在构造实例对象时,需要:
TestOpenBuilder.Build()或TestOpenBuilder.Build("","","");
如果将构造器封装在interface中,如这样所示:
public interface TestOpen { String getVirtualHost(); String getCapabilities(); boolean getInsist(); final class Build { private String t1; private String t2; private String t3; public TestOpen.Build t1(String t1){ this.t1=t1; return this; } public TestOpen.Build t2(String t2){ this.t2=t1; return this; } public TestOpen.Build t3(String t3){ this.t3=t3; return this; } public TestOpen build() { return new TestOpenImpl(this.t1,this.t2,this.t3); } } }
则我们在构造时,可以这样:
TestOpen testOpen = new TestOpen.Build().t1("haha").t2("21").t3("23").build();
这样做的好处:可以将接口与其构建器关联起来,方便使用。