Java初涉之6--浅谈反射

工场方法,没用反射前,如果有新增,就是要修改工场
/**
 * @author Rollen-Holt 设计模式之 工厂模式
 */
 
interface fruit{
    public abstract void eat();
}
 
class Apple implements fruit{
    public void eat(){
        System.out.println("Apple");
    }
}
 
class Orange implements fruit{
    public void eat(){
        System.out.println("Orange");
    }
}
 
// 构造工厂类
// 也就是说以后如果我们在添加其他的实例的时候只需要修改工厂类就行了
class Factory{
    public static fruit getInstance(String fruitName){
        fruit f=null;
        if("Apple".equals(fruitName)){
            f=new Apple();
        }
        if("Orange".equals(fruitName)){
            f=new Orange();
        }
        return f;
    }
}
class hello{
    public static void main(String[] a){
        fruit f=Factory.getInstance("Orange");
        f.eat();
    }
 
}

//用了反射

package reflectTest;

public class ReflectT {
    
    public static void main(String[] args) {
        fruit f = Factory.getInstance("Apple");
        if(f != null){
            f.eat();
        }
    }

    
}

interface fruit{
    public abstract void eat();
}

class Apple implements fruit{
    @Override
    public void eat() {
      System.out.println("Apple");           
    }      
}

class Orange implements fruit{
    @Override
    public void eat() {
        // TODO Auto-generated method stub
        System.out.println("Orange");
    }
}

class Factory{
    public static fruit getInstance(String Name){
        fruit f = null;
        try {
            f = (fruit)Class.forName("reflectTest."+Name).newInstance();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return f; 
    }
}


你可能感兴趣的:(Java初涉之6--浅谈反射)