简单工厂模式有个问题,如果要新增一个功能的话,就需要去修改工厂类,这样做违背了设计模式的开闭原则。所以,我们为了解决这个问题,需要用到工厂方法模式。这样的话,如果我们要新增一个功能,只要新增一个工厂类就可以了。
工厂类的接口
public interface AnimalProvider {
public Animal produce();
}
类的接口
public interface Animal {
void eat();
}
实现类
public class Cat implements Animal{
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("Cat eat");
}
}
public class Dog implements Animal{
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("Dog eat");
}
}
工厂类
public class CatFactory implements AnimalProvider{
@Override
public Animal produce() {
// TODO Auto-generated method stub
return new Cat();
}
}
public class DogFactory implements AnimalProvider{
@Override
public Animal produce() {
// TODO Auto-generated method stub
return new Dog();
}
}
测试类
public class AnimalTest {
public static void main(String[] args) {
CatFactory catFactory = new CatFactory();
Animal animal=catFactory.produce();
animal.eat();
}
}
输出:
Cat eat
如果要对程序进行拓展,只需要增加一个工厂类 implements AnimalProvider ,和一个实现类。
比如:
public class MouseFactory implements AnimalProvider{
@Override
public Animal produce() {
// TODO Auto-generated method stub
return new Mouse();
}
}
public class Mouse implements Animal{
@Override
public void eat() {
// TODO Auto-generated method stub
System.out.println("Mouse eat");
}
}
测试类:
public class AnimalTest {
public static void main(String[] args) {
MouseFactory mouseFactory = new MouseFactory();
Animal animal=mouseFactory.produce();
animal.eat();
}
}
输出:
Mouse eat