跳到主要内容

工厂模式

类的实例化过程交给工厂来完成,而不是直接实例化对象。这种方法提高了代码的灵活性和可维护性,使得系统更容易扩展和管理。

public abstract class Animal {
public abstract String makeSound();
}

public class Dog extends Animal {
@Override
public String makeSound() {
return "Bark";
}
}

public class Cat extends Animal {
@Override
public String makeSound() {
return "Meow";
}
}

public class AnimalFactory {
public Animal createAnimal(String type) {
if ("Dog".equalsIgnoreCase(type)) {
return new Dog();
} else if ("Cat".equalsIgnoreCase(type)) {
return new Cat();
}
throw new IllegalArgumentException("Invalid animal type");
}
}

public class Main {
public static void main(String[] args) {
AnimalFactory animalFactory = new AnimalFactory();

Animal animal1 = animalFactory.createAnimal("Dog");
System.out.println("Animal 1: " + animal1.makeSound());

Animal animal2 = animalFactory.createAnimal("Cat");
System.out.println("Animal 2: " + animal2.makeSound());
}
}

实现

您可以在以下链接中找到完整的实现代码:

https://github.com/sumingcheng/Java-Learning/tree/main/src/com/DesignPattern/factory