2016-07-27 99 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)。

我希望它能帮助你。