在我的一个项目中,我必须实现Factory设计模式来解决特定问题。
我有一个父接口和两个子接口。在下一个阶段,我必须创建一个工厂,它将根据给定的输入返回特定类的实例。
请参阅下面的示例代码,该代码解释了我的问题和示例图。
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 :(得分:2)
您的问题与工厂模式没有直接关系。您宣布Animal
,然后希望将其视为Dog
。无论你如何创建它,你都需要使它Dog
来调用狗狗方法。
您有很多选择可以解决此问题。以下是一些备选方案。
使用单独的方法创建Animal
的不同扩展名。因此,工厂中的Animal getInstance(AnimalType type)
和Dog getDog()
方法不是Cat getCat()
,而是Animal
。鉴于工厂需要了解所有这些类别,这对我来说似乎是最好的选择。
继续从您的工厂返回instanceof
个实例,然后使用“访客”模式以不同方式对待狗和猫。
使用{{1}}并施放以将动物视为狗或猫。在大多数情况下不建议这样做,但在某些情况下是合适的。
答案 1 :(得分:2)
我认为您的问题与 "General OO"
并非真正与 Factory
设计模式有关。现在让我们来看看你的三个界面: Animal
, Dog
和 Cat
。 Dog
和 Cat
是通过 Animal
界面实现的,并不代表他们拥有与差异实施完全相同的行为,我们可以确保他们会尊重 Animal
的行为。
例如:
Dog
和 Cat
具有相同的行为 eat()
Dog
的 woof()
行为 Cat
< / LI>
Cat
的 miaw()
行为 Dog
< / LI>
醇>
因此,当你实现简单工厂(根据设计模式的头部,它不是真正的设计模式,只是一个编程习语)来处理创建对象并返回 {{ 1}} 界面,表示您将 Animal
和 Dog
视为 Cat
具有相同的行为 Animal
。这就是为什么你不能在你的代码中做这样的事情
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()
,另一个用于 Dog
< / LI>
Cat
强加给 Animal
或 Dog
,然后使用他们的功能Cat
和 Dog
)。< / LI>
醇>
我希望它可以帮到你。