手记

java Factory 传入的对象是啥就拿到对应实例调用对应方法

package com.curtis.test.factory;

interface IFruit {  
    public void eat();
}

class Orange implements IFruit {
    @Override
    public void eat() {
        System.out.println("吃橙子.");
    }
}

class Apple implements IFruit {
    @Override
    public void eat() {
        System.out.println("吃苹果.");
    }
}

public class TestFactory {
    public static void main(String[] args) {
        // IFruit apple=new Apple();
        // apple.eat();
        // IFruit orange=new Orange();
        // orange.eat();
        IFruit apple = Factory.getInstance(Apple.class);
        IFruit orange = Factory.getInstance(Orange.class);
        orange.eat();
        apple.eat();
    }
}
package com.curtis.test.factory;

public class Factory {

    public static <T> T getInstance(Class<T> cls) {
        try {
            return cls.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
0人推荐
随时随地看视频
慕课网APP