[color=darkblue] 简单工厂模式的主要目的是实现对象实例的统一创建,方便资源对象的统一管理。
简单工厂模式的实现方式如下:[/color]
简单工厂模式的实现方式如下:[/color]
/**
* 水果接口定义
* @author zhma
*/
public interface Fruit {
public void grow();
public void sell();
}
/**
* 苹果
* @author zhma
*/
public class Apple implements Fruit {
public void grow() {
System.out.println("苹果在生长……");
}
public void sell() {
System.out.println("苹果被卖掉……");
}
}
/**
* 香蕉
* @author zhma
*/
public class Banana implements Fruit {
public void grow() {
System.out.println("香蕉在生长.");
}
public void sell() {
System.out.println("香蕉被卖掉.");
}
}
/**
* 水果工厂
* @author zhma
*/
public class FruitFactory {
public static Fruit getFruit(String className){
Fruit fruit =null;
try {
fruit = (Fruit)Class.forName(className).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return fruit;
}
}
/**
* 测试水果工厂,从工厂中获取一个苹果实例
* @author zhma
*/
public class TestFruit {
public static void main(String[] args) {
Fruit apple = FruitFactory.getFruit("com.mzh.common.Apple");
apple.grow();
apple.sell();
}
}