1.产品接口,产品实现类和简单工厂一样
2.工厂接口类
3.工厂实现类
4.demo
package Factory;
public interface Animal {
public void makeSound();
}
package Factory;
public class Dog implements Animal{
@Override
public void makeSound() {
System.out.println("wang");
}
}
package Factory;
public class Cat implements Animal{
@Override
public void makeSound() {
System.out.println("miao");
}
}
2.工厂接口类
package Factory;
public interface AnimalFactory {
public Animal createAnimal();
}
3.工厂实现类
package Factory;
public class DogFactory implements AnimalFactory{
@Override
public Animal createAnimal() {
return new Dog();
}
}
package Factory;
public class CatFactory implements AnimalFactory{
@Override
public Animal createAnimal() {
return new Cat();
}
}
4.demo
package Factory;
public class AnimalFactoryDemo {
public static void main(String[] args){
AnimalFactory dogfactory = new DogFactory();
dogfactory.createAnimal().makeSound();
AnimalFactory catfactory = new CatFactory();
catfactory.createAnimal().makeSound();
}
}