抽象工厂模式

Animal创建接口类

public interface Animal {
    void sounds();
}

实体类实现Animal接口

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

Food创建接口类

public interface Food {
    void eat();
}

实体类实现Food接口

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

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

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

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

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;
    }
}
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;
    }
}

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

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;
    }
}

测试类检验成果

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();
    }
}

输出结果

狗叫汪汪
猫叫喵喵
狗喜欢吃骨头
猫喜欢吃鱼

发表评论

邮箱地址不会被公开。 必填项已用*标注