所以,这个代码元素有可能变得非常难看。有可能在每个if语句中向列表中添加多个元素以及更多if / else语句。设计这段代码的最佳模式或方法是什么?我正在考虑责任链,但这意味着要将列表传递到各地,这不是最好的甚至是建设者模式?有什么想法吗??
List<String> aList = new ArrayList<>();
if (something.contains(Effect.HARD)) {
aList.add("");
}
if (something.contains(Effect.REFLECT)) {
aList.add("");
aList.add("");
} else {
aList.add("no reflect");
}
if (something.contains(Effect.OUTLINE)) {
aList.add("something");
}
if (something.contains(Effect.GRADIENT)) {
aList.add("gradient");
} else {
aList.add("no gradient");
}
使用visitor(链接到维基百科页面)。
这是一些轻松愉快的示例代码:
public interface Visilator
{
// Process the stuff and, maybe, add an element to the kerplungy list.
void doStuff(Stuff stuff, List<Kerplungy> kerplungyList);
}
public class Kerplungilator
{
// Actually create this however you choose.
@Autowired
private List<Visilator> visilatorList;
public List<Kerplungy> processStuffs(final Stuff stuff)
{
final List<Kerplungy> returnValue = LinkedList<>(); // ArrayList is for chumps.
for (final Visilator current : visilatorList)
{
current.doStuff(Stuff, returnValue);
}
return returnValue;
}
}
public clss HootVisilator
implements Visilator
{
public void doStuff(
@NotNull final Stuff stuff,
@NotNull final List<Kerplungy> kerplungyList)
{
if (stuff.hoot())
{
final Kerplungy hootKerplungy = new Kerplungy("hoot");
kerplungyList.add(hootkerplungy);
}
else
{
System.out.println("not hoot");
}
}
}
通常你会看到用多态代码替换那些丑陋的条件,但这在这里不能很好地工作,因为条件(something.contains(...)
)不是基于对象的类型。你可以将它们变成对象,但这也不是一个优雅的解决方案。可以使用Builder和Visitor,但我很怀疑你的代码会更具可读性。