在工厂模式中,你不需要关系水果是怎么种出来的,你只要知道水果的名字,将名字交给工厂,你就可以得到水果。
我们首先创建一个水果的接口,所有水果都有一个被吃了的方法,如下代码所示:
package com.fruitInterface.demo;
public interface Fruit {
public void eaten();
}
我们通过水果的接口定义好具体的水果类(苹果和橘子),在具体的水果方法中,我们实现了“被吃”的方法
package com.fruit.demo;
import com.fruitInterface.demo.Fruit;
public class Apple implements Fruit{
@Override
public void eat() {
System.out.println("I am apple,I am eaten");
}
}
package com.fruit.demo;
import com.fruitInterface.demo.Fruit;
public class Orange implements Fruit{
@Override
public void eat() {
System.out.println("I am orange,I am eaten");
}
}
最后我们的main方法,使用工厂来“吃苹果”
package com.main.demo;
import com.fruit.demo.Apple;
import com.fruitFactory.demo.FactoryDemo;
public class ReflectDemo {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
// TODO Auto-generated method stub
Apple apple = (Apple) FactoryDemo.getFruit("com.fruit.demo.Apple");
apple.eaten();
}
}