工厂模式
简单例子Demo
-
创建一个 接口类Animals.java
public interface Animals { void cry(); }
-
创建Dog、Cat、Bird等类实现Animals接口
Dog.java
public class Dog implements Animals { @Override public void cry() { System.out.println("Dog cry()"); } }
Cat.java
public class Cat implements Animals { @Override public void cry() { System.out.println("Cat cry()"); } }
Bird.java
public class Bird implements Animals { @Override public void cry() { System.out.println("Bird cry()"); } }
-
创建动物工厂类 AnimalFactory.java
public class AnimalFactory { public Animals getAnimals(String animalType) { if (animalType == null) { return null; } if (animalType.equalsIgnoreCase("dog")) { return new Dog(); }else if (animalType.equalsIgnoreCase("cat")) { return new Cat(); }else if (animalType.equalsIgnoreCase("bird")) { return new Bird(); } return null; } }
-
测试Demo
public class Demo { public static void main(String[] args) { AnimalFactory animalFactory = new AnimalFactory(); Animals animals1 = animalFactory.getAnimals("dog"); animals1.cry(); Animals animals2 = animalFactory.getAnimals("cat"); animals2.cry(); Animals animals3 = animalFactory.getAnimals("bird"); animals3.cry(); } }