读书人

易学设计方式七 简单工厂(Simple Fac

发布时间: 2012-11-08 08:48:11 作者: rapoo

易学设计模式七 简单工厂(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();}}


输出结果
Apple has been planted
Apple is growing
Apple has been havested
Strawberry has been planted

读书人网 >软件开发

热点推荐