如何才能提高代码如下设计:摆脱if语句来提高代码的设计
class Foo {
public Configuration configure() {
return new Configuration().withPropertyA().withPropertyB();
}
}
class Configuration{
private boolean propertyA = false;
private boolean propertyB = false;
public Configuration withPropertyA() {
this.propertyA = true;
return this;
}
public Configuration withPropertyB() {
this.propertyB = true;
return this;
}
public boolean hasPropertyA() {
return this.propertyA;
}
public boolean hasPropertyB() {
return this.propertyB;
}
...
}
class Client{
public void someMethod(Configuration config) {
if (config.hasPropertyA() {
doStuffA();
}
if (config.hasPropertyB() {
doStuffB();
}
//...
}
}
即,配置类包含一些标志呼叫者(Client
)告诉给调用者这“事物”需要配置。客户知道如果设置了每个标志,该怎么做。我想摆脱Client
中的if语句以及在Configuration
实例中简单设置布尔标志的概念。你能提出一个更“通用”和面向对象的方法吗?
亲切的问候
代码优化通常是无关紧要的...... –