public class BuilderPattern { private String name ; private int age; private String email; BuilderPattern(Builder builder){ this.name = builder.name; this.age = builder.age; this.email = builder.email; } public void printinfo(){ System.out.println("name:"+this.name+"-----age:"+this.age+"----email:"+this.email); } public static void main(String[] args) { BuilderPattern bp = new BuilderPattern.Builder().setName("javaeye").setAge(23).setEamil("aa@qq.com").build(); bp.printinfo(); } private static class Builder{ private String name ; private int age; private String email; public BuilderPattern build(){ return new BuilderPattern(this); } public Builder(){ } public Builder setName(String name){ this.name = name; return this; } public Builder setAge(int age){ this.age = age; return this; } public Builder setEamil(String email){ this.email = email; return this; } } }
?这种方式适合对于复杂的对象,简单的调用方式,避免了一行一行的setXxxx或者是 糊里糊涂的构造
原文:http://maclab.iteye.com/blog/2264759