易学设计模式七 简单工厂(Simple Factory)
简单工厂模式是类的创建模式,又叫做静态工厂方法(Static Factory Method)模式,是由一个工厂对象决定创建出哪一种产品类的实例。
本例子一共有七个类,Fruit是抽象类,Apple,Grape,Strawberry是继承了Fruit的具体类,FruitGardener是提供工厂方法(factory)的类,BadFruitException是异常类,Client是测试类。
抽象类 或者 接口
public class Client {public static void main(String[] args) throws BadFruitException {Fruit apple = FruitGardener.factory("apple");apple.plant();apple.grow();apple.harvest();Fruit strawberry = FruitGardener.factory("strawberry");strawberry.plant();}}