在上篇文章中讲到,代码需要充分解耦,像GPS、sensor和序列化工具这些变化的东西,我们通过外面配置来驱动业务,避免使用hard code。例如:GPS我们是用百度呢还是高德呢,我们用TripSetting来设置,这个Setting可以从服务端获取到,存储到本地,那么这个Setting应该和谁绑定呢,因为GPSTracker外层是TripTracker,所有我们setting和triptracker是一对一的对应关系。
public class TripManager {
private TripTracker mTracker;
private TripSetting mSettings;
public void startTrip() {
mTracker = new TripTracker(mSettings);
mTracker.startTracker();
}
public void stopTrip() {
mTracker.stopTracker();
}
}
在TripTracker中,我们利用Builder模式来设置参数,把GpsTracker的构造函数改成private,不让从外面进行实例化,这样就能避免参数设置问题,防止少设置参数。
public void startTracker() {
gpsTracker = new GpsTracker.Builder().setOnGpsChangedListener(this).
setUserGps(true).
setUseNetwork(true).
setType(mSettings.gpsType).build();
gpsTracker.startLocation();
sensorTracker = new SensorTracker.Builder().setOnSensorChangedListener(this).
setSensorType(mSettings.sensorTypes).
setSamplePeriodUs(mSettings.samplingPeriodUs).build();
sensorTracker.startSensor();
mtripWriter = new TripWriter();
}
GpsTrackerl里面的Builder模式
public class GpsTracker {
private onGpsChangedListener mlistener;
private boolean mUserGps;
private boolean mUseNetwork;
private int type;
private GpsTracker(Builder builder) {
type = builder.type;
}
public void startLocation() {
}
public void stopLocation() {
}
public static class GpsEntity {
public int timestamp;
public long lat;
public long lan;
}
interface onGpsChangedListener {
void onGpsChanged(GpsEntity gpsEntity);
}
public static class Builder {
private boolean userGps;
private boolean useNetwork;
private int type;
private onGpsChangedListener mlistener;
public Builder setOnGpsChangedListener(onGpsChangedListener listener) {
this.mlistener = listener;
return this;
}
public Builder setUserGps(boolean userGps) {
this.userGps = userGps;
return this;
}
public Builder setUseNetwork(boolean useNetwork) {
this.useNetwork = useNetwork;
return this;
}
public Builder setType(int type) {
this.type = type;
return this;
}
public GpsTracker build() {
return new GpsTracker(this);
}
}
}
解耦不?解耦。。。。可以分配任务了。。。哈哈