簡體   English   中英

良好實踐/設計模式是否可以解決嵌套問題?

[英]Good practice / design pattern to resolve the nested if else?

目前,我有這樣的代碼:

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

現在,我還有一個附加要求-我要進行相同的檢查,但是要打印,我需要插入DB。

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
      }
   } 
}

顯然,這引起了很多混亂。 我的面向對象編程告訴了我一個新主意。

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

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

代碼看起來更簡潔。 但是,考慮到我能想到的,有人能指出我在這種情況下能解決的確切設計模式嗎?

您可以執行許多方法。 這實際上取決於您要如何組織代碼。 有不止一種好的方法。 如果我給您一些簡短的答案,例如“抽象”,“多態”,“關注點分離”等。這是一個示例,不需要/不要求:

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

一個簡單的多態示例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM