2016-02-26 32 views
-1

目前我有這樣的代碼:好的做法/設計模式來解決嵌套的if else?

for (each item) { 
    if (item == 'x') { 
     print 
    } 
    if (item == 'y) { 
     print 
    } 
} 

現在,我有一個額外的要求 - 我想同樣的檢查,但不是印刷的,我需要在數據庫中插入。

for (each item) { 
    if (item == 'x') { 
     insertDB 
    } 
    if (item == 'y) { 
     insertDB 
    } 
} 

這重複的代碼,所以標誌來我的思想。

for (each item) { 
    if (item == 'x') { 
     if (insertDB) { 
      insertDB 
     } else { 
      print 
     } 
    } 
    if (item == 'y) { 
     if (insertDB) { 
     insertDB 
     } else { 
     print 
     } 
    } 
} 

這明顯導致了很多if-else混亂。我的面向對象編程告訴我一個新想法。

for (each item) { 
    if (item == 'x') { 
     obj.doItemXAction(); 
    } 
    if (item == 'y) { 
     obj.doItemXAction(); 
    } 
} 

Object obj = new PrintObj(); 
Object obj = new DBInsertObj(); 

代碼看起來乾淨多了。但是,考慮到我能想到的,任何人都可以指出我在這種情況下處理的確切設計模式?

+1

看起來有點像'戰略模式'或至少是一個候選人.. http://www.tutorialspoint.com/design_pattern/strategy_pattern.htm –

回答

1

多態性的一個簡單例子:

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(); 
    } 
} 

你可以把它更進了一步,並與InsertablePrintable延長Actionable

1

有很多方法可以做。這真的取決於你想如何組織你的代碼。有不止一種好方法。如果我給你模糊的簡短回答,「抽象」,「多態」,「關注點分離」等。以下是一個例子,如果沒有要求/其他:

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(); 
      }   
    } 
}