我们需要的是使用Builder内部类复制相同的层次结构。当我们需要方法链接时,我们需要一个
getThis()返回层次结构叶对象的方法。为了将其类型向上传递给层次结构,父类具有一个通用类
T,并且叶子与其
T自身绑定。
它确保类型安全,并避免由于未初始化的强制性参数或拼写错误以及漂亮的流畅接口而引发任何异常。但是,它代表URL这样的简单结构,这是一个非常昂贵且复杂的设计。我希望它对某人有用-
我更喜欢最后的字符串连接。
RequestUrl:
public abstract class RequestUrl{ public static abstract class Builder<T extends Builder<T>>{ protected String output; protected boolean sensor; //Optional parameters can have default values protected String lang = "en"; public Builder(String output, boolean sensor){ this.output = output; this.sensor = sensor; } public T lang(String lang){ this.lang = lang; return getThis(); } public abstract T getThis(); } final private String output; final private boolean sensor; final private String lang; protected <T extends Builder<T>> RequestUrl(Builder<T> builder){ this.output = builder.output; this.sensor = builder.sensor; this.lang = builder.lang; } // other logic...}
GeopreRequestUrl:
public abstract class GeopreRequestUrl extends RequestUrl { public static abstract class Builder<T extends Builder<T>> extends RequestUrl.Builder<Builder<T>>{ protected Bounds bounds; protected String region = "us"; public Builder(String output, boolean sensor){ super( output, sensor ); } public T bounds(Bounds bounds){ this.bounds = bounds; return getThis(); } public T region(String region){ this.region = region; return getThis(); } @Override public abstract T getThis(); } final private Bounds bounds; final private String region; protected <T extends Builder<T>> GeopreRequestUrl(Builder<T> builder){ super (builder); this.bounds = builder.bounds; this.region = builder.region; } // other logic...}
DirectGeopreRequestUrl:
public class DirectGeopreRequestUrl extends GeopreRequestUrl { public static class Builder<Builder> extends GeopreRequestUrl.Builder<Builder>{ protected String address; public Builder(String output, boolean sensor, String address){ super( output, sensor ); this.address = address; } @Override public Builder getThis(){ return this; } public DirectGeopreRequestUrl build(){ return new DirectGeopreRequestUrl(this); } } final private String address; protected DirectGeopreRequestUrl(Builder builder){ super (builder); this.address = builder.address; } // other logic...}
ReverseGeopreRequestUrl:
public class ReverseGeopreRequestUrl extends GeopreRequestUrl { public static class Builder<Builder> extends GeopreRequestUrl.Builder<Builder>{ protected Coord location; public Builder(String output, boolean sensor, Coord location){ super( output, sensor ); this.location = location; } @Override public Builder getThis(){ return this; } public ReverseGeopreRequestUrl build(){ return new ReverseGeopreRequestUrl(this); } } final private Coord location; protected ReverseGeopreRequestUrl(Builder builder){ super (builder); this.location = builder.location; } // other logic...}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)