标签:code instance throw bsp rri interface blog 工厂 factor
//使用new关键字创建对象的缺点是耦合度太高,工厂设计模式利用Java的反射机制来实例化对象降低了这种耦合度
package cn.buaa; import java.util.Date; interface Fruit{ public void eat(); } class Apple implements Fruit{ @Override public void eat() { System.out.println("吃苹果"); } } class Orange implements Fruit{ @Override public void eat() { System.out.println("吃橘子"); } } class Factory{ public static Fruit getInstance(String className){ Fruit f = null; try{ Class<?> cla = Class.forName(className); f = (Fruit)cla.newInstance(); }catch(Exception e){ e.printStackTrace(); } return f; } } public class Hello { public static void main(String[] args) throws Exception { Fruit f = Factory.getInstance("cn.buaa.Orange"); f.eat(); } }
标签:code instance throw bsp rri interface blog 工厂 factor
原文地址:http://www.cnblogs.com/StanLong/p/6413846.html