简单工厂(静态工厂方法Static Factory Method模式)
简单工厂模式是由一个工厂对象来决定创造哪一种产品类的实例
简单工厂模式最大的优点在于工厂类中包含了必要的逻辑判断。
// 产品接口---水果接口
public interface Fruit {
public void plant();
}
// 产品----苹果类
public class Apple implements Fruit {
public void plant() {
System.out.println("plant apple!");
}
}
// 产品----草莓类
public class Strawberry implements Fruit {
public void plant() {
System.out.println("plant Strawberry!");
}
}
// 工厂异常类
public class BadFruitException extends Exception {
public BadFruitException(String msg) {
super(msg); // 调用父类的构造方法
}
}
// 工厂----园丁类
public class FruitGardener {// 静态工厂方法
public static Fruit factory(String which) throws BadFruitException {
if (which.equalsIgnoreCase("apple")) {
return new Apple();
} else if (which.equalsIgnoreCase("strawberry")) {
return new Strawberry();
} else {
throw new BadFruitException("Bad fruit request");
}
}
}
// 测试类
public class TestApp {
private void test(String fruitName) {
try {
Fruit f = FruitGardener.factory(fruitName);
System.out.println("恭喜!生产了一个水果对象:" + fruitName);
} catch (BadFruitException e) {
System.out.println("工厂目前不能生产产品:" + fruitName);
System.out.println(e.getMessage());// 输出异常信息
}
}
public static void main(String args[]) {
TestApp t = new TestApp();
t.test("apple");
t.test("strawberry");
t.test("car"); // 此处会抛异常,水果工厂能生产car(轿车)吗!
}
}