一、简单工厂模式类图
二、具体例子
// 水果接口
public interface Fruit {
void display();
}
// 苹果,实现水果接口
public class Apple implements Fruit {
@Override
public void display() {
System.out.println("I am apple");
}
}
// 橘子
public class Orange implements Fruit {
@Override
public void display() {
System.out.println("I am orange");
}
}
// 简单工厂类
public class FruitFactory {
public static Fruit createFruit(String name) {
Fruit fruit = null;
switch (name) {
case "apple":
fruit = new Apple();
break;
case "orange":
fruit = new Orange();
break;
}
return fruit;
}
}
// 客户端
public class Client {
public static void main(String[] args) {
Fruit apple = FruitFactory.createFruit("apple");
Fruit orange = FruitFactory.createFruit("orange");
apple.display();
orange.display();
}
}
较为简单。