2016-07-27 107 views
0

在我的一個項目中,我必須實施工廠設計模式來解決特定問題。工廠設計模式和鑽石OOP問題

我有一個父接口和兩個子接口。在下一個階段,我必須創建一個工廠,它將根據給定的輸入返回特定類的實例。

請參閱下面的示例代碼,其中解釋了我的問題以及示例圖。

範例圖

enter image description here

示例代碼

enum AnimalType{ DOG, CAT } 

Class Factory{ 
    public Animal getInstance(AnimalType animalType){ 
     Animal animal = null; 
     switch(animalType){ 
      case DOG: animal = new Dog(); 
       break; 

      case CAT: animal = new Cat(); 
       break; 
      default: 
       break; 
     } 
     return animal; 
    } 
} 

/*Actual Problem */ 
Animal animal = Factory.getInstance(AnimalType.DOG); 

    /* When I use any IDE like IntellijIdea or Eclipse it only provides eat() method after animal and dot (ie. animal.) */ 
animal.<SHOULD PROVIDE eat() and woof() from Dog> but it is only providing eat() 

任何意見,解決這個問題?或者,我應該考慮任何其他設計模式來解決這個問題嗎?

+0

它被宣佈爲動物,而不是狗。宣佈'動物'爲'狗',然後嘗試。 – ifly6

回答

2

您的問題與工廠模式沒有直接關係。您聲明Animal,然後想將其視爲Dog。無論你如何創建它,你都需要使它成爲Dog來調用小狗的方法。

你有很多選擇來解決這個問題。這裏有幾個選擇。

  1. 有單獨的方法來創建Animal的不同擴展名。所以,而不是Animal getInstance(AnimalType type)你會在工廠有Dog getDog()Cat getCat()方法。鑑於工廠需要知道所有這些類,無論如何這似乎是對我來說最好的選擇。

  2. 繼續從您的工廠返回Animal實例,但隨後使用「訪問者」模式以不同方式對待狗和貓。

  3. 使用instanceof和鑄造將動物視爲狗或貓。這在大多數情況下不推薦,但在某些情況下適用。

2

我認爲你的問題是關係到"General OO"不是真正的Factory設計模式。現在,讓我們來看看你的三個接口:AnimalDogCat。該DogCat實現了Animal接口,這並不意味着他們有正好與差異實現同樣的行爲,我們可以保證的是他們會尊重Animal行爲。

例如:

  1. DogCat將具有相同的行爲是eat()
  2. Dog具有不存在的woof()行爲在Cat
  3. Cat具有不中Dog

因此存在,當你(根據頭設計模式的實現簡單工廠一miaw()行爲它不是真正的設計模式,只是一個編程習慣用法)來處理創建對象並返回Animal接口,這意味着你正在考慮的DogCatAnimal具有相同行爲eat()。這就是爲什麼你不能做這樣的出頭在你的代碼

/*Actual Problem */ 
Animal animal = Factory.getInstance(AnimalType.DOG); 

    /* When I use any IDE like IntellijIdea or Eclipse it only provides eat() method after animal and dot (ie. animal.) */ 
animal.<SHOULD PROVIDE eat() and woof() from Dog> but it is only providing eat() 

在我看來,有一些可能的實施

  1. 爲了簡單起見,你可以創建2 簡單工廠,一個爲Dog等是Cat
  2. 如果你知道你W¯¯螞蟻,你可以施放AnimalDogCat,然後用它們的功能
  3. 實現抽象工廠模式,它會提供和創造產品家族(Dog抽象接口Cat)。

我希望它能幫助你。