利用反射实现了程序解耦合的目的,同时程序的可扩展性也非常强。
无参构造
interface Fruit{
void eat();
}
class Apple implements Fruit{
public void eat(){
System.out.println("eat apple");
}
}
class Orange implements Fruit{
public void eat(){
System.out.println("eat orange");
}
}
class Factory{
public static Fruit getInstance(String className){
Fruit fruit = null;
try{
fruit = (Fruit) Class.forName(className).newInstance();
}catch (Exception e){}
return fruit;
}
}
public class Main {
public static void main(String[] args) {
Fruit fruitA = Factory.getInstance("Apple");
Fruit fruitB = Factory.getInstance("Orange");
fruitA.eat();
fruitB.eat();
}
}
有参构造
import java.lang.reflect.Constructor;
interface Fruit{
void eat();
}
class Apple implements Fruit{
private String name;
private int price;
public Apple(String name, int price){
this.name = name;
this.price = price;
}
public void eat(){
System.out.println(this.name + " " + this.price);
}
}
class Orange implements Fruit{
private String name;
private int price;
public Orange(String name, int price){
this.name = name;
this.price = price;
}
public void eat(){
System.out.println(this.name + " " + this.price);
}
}
class Factory{
public static Fruit getInstance(String className, int price){
Fruit fruit = null;
try{
Class <?> cls = Class.forName(className);
Constructor <?> con = cls.getConstructor(String.class, int.class);
fruit = (Fruit) con.newInstance(className, price);
}catch (Exception e){}
return fruit;
}
}
public class Main {
public static void main(String[] args) {
Fruit fruitA = Factory.getInstance("Apple",5);
Fruit fruitB = Factory.getInstance("Orange",4);
fruitA.eat();
fruitB.eat();
}
}