[英]Good practice / design pattern to resolve the nested if else?
Currently I have a code like this: 目前,我有这样的代码:
for (each item) {
if (item == 'x') {
print
}
if (item == 'y) {
print
}
}
Now, I there is an additional requirement - I want the same checks but instead of printing, I need to insert in DB. 现在,我还有一个附加要求-我要进行相同的检查,但是要打印,我需要插入DB。
ie 即
for (each item) {
if (item == 'x') {
insertDB
}
if (item == 'y) {
insertDB
}
}
This has duplicated code, so flags come to my thought. 这有重复的代码,所以我想到了标志。
for (each item) {
if (item == 'x') {
if (insertDB) {
insertDB
} else {
print
}
}
if (item == 'y) {
if (insertDB) {
insertDB
} else {
print
}
}
}
This has clearly caused a lot of if-else clutter. 显然,这引起了很多混乱。 My Object oriented programming tells me a new idea. 我的面向对象编程告诉了我一个新主意。
for (each item) {
if (item == 'x') {
obj.doItemXAction();
}
if (item == 'y) {
obj.doItemXAction();
}
}
Object obj = new PrintObj();
Object obj = new DBInsertObj();
Code looks much cleaner. 代码看起来更简洁。 But, given what I could think off, can anyone point me to exact design pattern which deals in situations like this ? 但是,考虑到我能想到的,有人能指出我在这种情况下能解决的确切设计模式吗?
There are so many ways that you can do. 您可以执行许多方法。 It's really depending on how you wanna organize your code. 这实际上取决于您要如何组织代码。 There are more than one good ways. 有不止一种好的方法。 If I give you vague short answers, "Abstraction", "Polymorphism", "Separation of concerns", etc. Here is one example, no if/else is required: 如果我给您一些简短的答案,例如“抽象”,“多态”,“关注点分离”等。这是一个示例,不需要/不要求:
interface AnimalBehavior {
void eat();
void drink();
}
abstract class Animal implements AnimalBehavior {
abstract void eat();
abstract void drink();
}
class Bear extends Animal {
void eat() {
// bear eats cookies
}
void drink() {
// bear drinks juice
}
}
class Chicken extends Animal {
void eat() {
// chicken eats candy
}
void drink() {
// chicken drinks soda
}
}
class AnimalStats {
main () {
Animal chicken1 = new Chicken();
Animal chicken2 = new Chicken();
Animal bear1 = new Bear();
Animal bear2 = new Bear();
List<Animal> animals = Arrays.asList(chicken1, chicken2, bear1, bear2);
for(Animal animal: animals) {
animal.eat();
animal.drink();
}
}
}
A simpler example of polymorphism: 一个简单的多态示例:
public interface Actionable {
void doItemAction();
}
public class Item implements Actionable {
@Override
public void doItemAction() {
// insert or print
}
}
public static void main(Actionable... args) {
for (Actionable item : args) {
item.doItemAction();
}
}
You might take it a step further and extend Actionable
with Insertable
and Printable
. 您可能会更进一步,并使用Insertable
和Printable
扩展Actionable
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.