抽象工厂模式

Animal创建接口类

1
2
3
public interface Animal {
void sounds();
}

实体类实现Animal接口

1
2
3
4
5
6
public class Dog implements Animal {
@Override
public void sounds() {
System.out.println("狗叫汪汪");
}
}
1
2
3
4
5
6
public class Cat implements Animal {
@Override
public void sounds() {
System.out.println("猫叫喵喵");
}
}

Food创建接口类

1
2
3
public interface Food {
void eat();
}

实体类实现Food接口

1
2
3
4
5
6
public class Bone implements Food {
@Override
public void eat() {
System.out.println("狗喜欢吃骨头");
}
}
1
2
3
4
5
6
public class Fish implements Food {
@Override
public void eat() {
System.out.println("猫喜欢吃鱼");
}
}

AnimalFood对象创建抽象类来获取工厂

1
2
3
4
public abstract class AbstractFactory {
public abstract Animal getAnimal(String animal);
public abstract Food getFood(String food);
}

AnimalFood对象创建各自的工厂类继承AbstractFactory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class AnimalFactory extends AbstractFactory{

@Override
public Animal getAnimal(String animal) {
if("cat".equals(animal)){
return new Cat();
}
if ("dog".equals(animal)) {
return new Dog();
}
return null;
}

@Override
public Food getFood(String food) {
return null;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class FoodFactory extends AbstractFactory {

@Override
public Animal getAnimal(String animal) {
return null;
}

@Override
public Food getFood(String food) {
if("bone".equals(food)){
return new Bone();
}
if ("fish".equals(food)) {
return new Fish();
}
return null;
}
}

创建一个工厂创造器/生成器类,通过传递参数来获取对应工厂

1
2
3
4
5
6
7
8
9
10
11
public class FactoryProducer {
public static AbstractFactory getFactory(String choice){
if ("animal".equals(choice)) {
return new AnimalFactory();
}
if ("food".equals(choice)) {
return new FoodFactory();
}
return null;
}
}

测试类检验成果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class AbstractFactoryDemo {
public static void main(String[] args) {
AbstractFactory animalFactory = FactoryProducer.getFactory("animal");
Animal dog = animalFactory.getAnimal("dog");
dog.sounds();
Animal cat = animalFactory.getAnimal("cat");
cat.sounds();

AbstractFactory foodFactory = FactoryProducer.getFactory("food");
Food bone = foodFactory.getFood("bone");
bone.eat();
Food fish = foodFactory.getFood("fish");
fish.eat();
}
}

输出结果

1
2
3
4
狗叫汪汪
猫叫喵喵
狗喜欢吃骨头
猫喜欢吃鱼