2012-12-08 99 views
1

我有工厂模式的一个问题,当它与继承使用,工厂模式与继承

这是我的代码

public class Animal { 
    public int numberOfLegs() { return 2 ;} 
} 

public class Cat extends Animal { 
    public String getSound() {return "Maaaw";} 
} 
public class Dog extends Animal { 
    public String getSound() {return "woof";} 
} 

public class AnimalFactory { 
    public Animal getAnimal(String name){ 
    Animal an= null ; 
    if(name=="cat"){an = new Cat();} 
    else if(name=="dog"){an=new Dog();} 
    return an ; 
    } 
} 

public class FactoryDemo { 

    public static void main(String[] args) { 
    AnimalFactory anmF=new AnimalFactory(); 
    Animal anm=anmF.getAnimal("cat") ; 
    System.out.println("legs : "+anm.numberOfLegs()); // working fine 
    System.out.println("sound : "+anm.getSound()); // giving error 
    } 
} 

当我运行这一点,我不能去了getSound()方法。它给出了一个错误。

这将工作正常,如果我将Animal类定义为Abstract类,
但我想要如何处理Factory模式这样的情况。

+0

它有助于知道你得到了什么错误。请把它包含在你的问题中。 –

+1

如果您认为所有的动物都应该有声音,那么getSound()方法应该是Animal类的一部分。它与工厂模式没有任何关系。 –

回答

2

您包含的代码与Factory无关。如果你参考Factory Method Pattern那么,你作为OP的一部分实现的是一个不正确的实现。有两种“工厂”代码设计,一种是我之前指出的工厂方法模式(您的代码肯定不是这样),以及Effective Java书中推荐的工厂,这是Java JDK的选择设计,即valueOfcreate*方法。

8

您需要添加一个抽象方法getSound

public abstract class Animal { 
    public int numberOfLegs() { return 2 ;} 
    public abstract String getSound(); 
} 
+0

谢谢,是的,它解决了这个问题,但我想知道有没有什么办法可以做到这一点,而不需要定义Animal类作为Abstract? – user1573690

+0

您需要提供'getSound()'的默认实现。 –

2

你的代码更改为:

public abstract class Animal { 
    public int numberOfLegs() { 
     return 2; 
    } 

    public abstract String getSound(); 
} 


public class Cat extends Animal { 
    public String getSound() { 
     return "Maaaw"; 
    } 
} 

public class Dog extends Animal { 
    public String getSound() { 
     return "woof"; 
    } 
} 

public class AnimalFactory { 
    public Animal getAnimal(String name) { 

     Animal an = null; 
     if ("cat".equals(name)) { 
      an = new Cat(); 
     } else if ("dog".equals(name)) { 
      an = new Dog(); 
     } 
     return an; 
    } 
} 

您应添加抽象方法,并使用在你的工厂方法等于而不是使用对象上的==

+0

谢谢,是的,它解决了这个问题,但我想知道有没有什么办法可以做到这一点,而不需要将Animal类定义为Abstract? – user1573690

+0

当然。只需在动物中添加getSound的实现并移除抽象关键字即可。 – sorencito