Java 反射实例化对象(修改工厂模式)

时间:2020-12-30 09:21:29
interface Phone {
	public abstract void buy();
}

class Apple implements Phone {

	@Override
	public void buy() {
		System.out.println("买iPhone手机.....");
	}

}

class Android implements Phone {
	@Override
	public void buy() {
		System.out.println("买安卓手机.....");

	}
}

class Factory {
	public static Phone getInstance(String className) {
		Phone f = null;
		try {
			f = (Phone) Class.forName(className).newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return f;
	}
}

public class Demo {
	public static void main(String[] args) {
		Phone fruit = Factory.getInstance("ikvDemo.Apple");
		fruit.buy();
	}
}
Java 反射实例化对象(修改工厂模式)