[英]How to make this “cleaner”
这是我的问题。
我有一堆由Gson序列化的Configuration类。 它们都位于一个目录中,序列化/反序列化过程相似,我觉得我应该将代码移到父类中。
我最终想出了这个(我觉得它是可怕的人为):
FooConfiguration.java:
package com.bar.foo;
import java.io.File;
import java.io.IOException;
public interface FooConfiguration {
/**
* Saves the configuration object to disk
* @param location the location to save the configuration
*/
public void save(File location) throws IOException;
}
FooConfigurationAbstract.java:
package com.bar.foo;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import com.google.gson.Gson;
public abstract class FooConfigurationAbstract implements FooConfiguration {
File location;
Gson gson;
@Override
public void save(File location) throws IOException {
FileUtils.writeStringToFile(location, gson.toJson(this), "utf-8");
}
}
FooConfigurationImpl.java:
package com.bar.foo;
- snip imports -
public class FooConfigurationImpl extends FooConfigurationAbstract {
/**
* Whether or not the we should use the new Bar feature
*/
@Expose
public Boolean useBar = false;
- snip more configuration values -
}
FooConfigurationFactory.java:
package com.bar.foo;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class FooConfigurationFactory<T extends FooConfiguration> {
public static Gson gson = new GsonBuilder()
.setPrettyPrinting()
.excludeFieldsWithoutExposeAnnotation()
.create();
public Class<T> clazz;
public File basePath;
public FooConfigurationFactory(File basePath, Class<T> clazz) {
this.basePath = basePath;
this.clazz = clazz;
}
public T load(String location) throws IOException {
return this.load(location, FooConfigurationFactory.gson);
}
public T load(String location, Gson gson) throws IOException {
return gson.fromJson(
FileUtils.readFileToString(
new File(this.basePath, location), "utf-8"),
this.clazz);
}
}
用法示例:
this.config = new FooConfigurationFactory<FooConfigurationImpl>(this.configDir, FooConfigurationImpl.class).load("config.json");
我觉得这是我一生中见过的最难看的东西 。 我的方法是错误的,还是有更好的方法呢?
save
移动到单独的类来简化层次结构。 (我不认为将配置保存到磁盘是配置本身的责任。) 。
public class FooConfigurationService {
...
public void save(File location, FooConfiguration configuration) { ... }
public <T extends FooConfiguration> T load(File location, Class<? extends T> clazz) { ... }
}
...
FooConfigurationFactory factory = ...;
this.config = factory.load(location, FooConfigurationImpl);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.