隐藏系统复杂性,向外部提供一个可访问的接口
public interface DataSource {
interface Callback<T> {
void success(T data);
void error(String message);
}
void getSimpleData(Callback<String> callback);
}
public class LocalDataSource implements DataSource {
@Override
public void getSimpleData(Callback<String> callback){
// 从数据库中获取数据
}
}
public class RemoteDataSource implements DataSource {
@Override
public void getSimpleData(Callback<String> callback){
// 从网络中获取数据
}
}
public class DataRepository implements DataSource{
private DataSource localDataSource;
private DataSource remoteDataSource;
@Override
public void getSimpleData(Callback<String> callback){
localDataSource.getSimpleData(new Callback<String>(){
@Override
public success(String data){
if(Strings.isEmpty(data)){
remoteDataSource.geSimpleData(callback);
} else {
callback.success(data)
}
}
...
});
}
}
隐藏具体的数据来源,只对外提供获取数据的方法.
网友评论