Java的工厂设计模式实例/* *工厂类实例 *通过一个工厂类实现生产水果这个特征的对象 */ interface Fruit{//水果接口 public void eat(); }class Apple implements Fruit{//苹果类 public void eat(){ System.out.println("这个水果是个苹果!"); } }class Orange implements Fruit{//橘子类 public void eat(){ System.out.println("这个水果是个橘子!"); } }class Factory{//工厂生产对象实例 public static Fruit getInstance(String fruit_name){ Fruit f = null;
if("apple".equals(fruit_name)){ f = new Apple(); } if("orange".equals(fruit_name)){ f = new Orange(); } return f; }}public class Factory_test{ public static void main(String args[]){ Fruit f = null; f = Factory.getInstance(args[0]);//通过外部输入参数访问,如java Factory_test apple if(f!=null){ f.eat(); } }}本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-05/131218.htm