角色:
- Buidler 抽象建造者
- ConcreteBuilder 具体建造者
- Director 指挥者(可以省略)
- Product 产品
1. 抽象产品类University
public abstract class University {
protected String uName;
protected int uAge;
protected String uAddress;
protected University() {
}
public abstract void setName(String name);
public abstract void setAge(int age);
public abstract void setAddress(String address);
@Override
public String toString() {
return this.getClass().getSimpleName() + ":\n{" +
"\n 学校:" + uName +
"\n 校龄:" + uAge +
"\n 地址:" + uAddress +
"\n}";
}
}
2.抽象建造者类UniversityBuilder
public abstract class UniversityBuilder<T extends University> {
public abstract T builder();
public abstract void setName(String name);
public abstract void setAge(int age);
public abstract void setAddress(String address);
}
3.具体产品类HenanUniversity
public class HenanUniversity extends University {
protected HenanUniversity() {
}
@Override
public void setName(String name) {
uName = name;
}
@Override
public void setAge(int age) {
uAge = age;
}
@Override
public void setAddress(String address) {
uAddress = address;
}
}
4.具体建造者HenanUniversityBuilder
public class HenanUniversityBuilder extends UniversityBuilder <HenanUniversity>{
private HenanUniversity henanUniversity = new HenanUniversity();
@Override
public HenanUniversity builder() {
return henanUniversity;
}
@Override
public void setName(String name) {
henanUniversity.setName(name);
}
@Override
public void setAge(int age) {
henanUniversity.setAge(age);
}
@Override
public void setAddress(String address) {
henanUniversity.setAddress(address);
}
}
5.指挥者HenanUniversityDirector
public class HenanUniversityDirector {
private HenanUniversityBuilder builder;
public HenanUniversityDirector(HenanUniversityBuilder builder) {
this.builder = builder;
}
public void construct(String name, int age , String address){
builder.setName(name);
builder.setAge(age);
builder.setAddress(address);
}
}
6.测试
public class BuilderDemo {
public static void main(String[]args){
HenanUniversityBuilder builder = new HenanUniversityBuilder();
HenanUniversityDirector director = new HenanUniversityDirector(builder);
director.construct("河南大学",104,"河南开封");
HenanUniversity henanUniversity = builder.builder();
System.out.println(henanUniversity);
}
}
运行结果:
HenanUniversity: { 学校:河南大学 校龄:104 地址:河南开封 }
挖坑。这里并不了解实际的使用场景。鸿洋大神的封装OkHttpUtils使用到了建造者模式,学习查看OkHttpUtls如何封装的时候,一开始代码看的有点懵,慢慢才看懂。这里简单记录一下。希望以后再看到采用Builder模式封装的库可以有些帮助。以后对设计模式有些了解后,再来补充。
2016.08.22 17:06