创建Apple产品:
package SimpleFactory; /** * 类说明 * * <pre> * Modify Information: * Author Date Description * ============ =========== ============================ * DELL 2017年2月4日 Create this file * </pre> * */ public class Apple implements Fruit{ /* * 简单工程模式 */ public void get() { System.out.println("get Apple"); } } 创建Banana:package SimpleFactory; /** * 类说明 * * <pre> * Modify Information: * Author Date Description * ============ =========== ============================ * DELL 2017年2月4日 Create this file * </pre> * */ public class Banana implements Fruit { public void get() { System.out.println("get Banana"); } }
水果接口:
package SimpleFactory; /** * 类说明 * * <pre> * Modify Information: * Author Date Description * ============ =========== ============================ * DELL 2017年2月4日 Create this file * </pre> * */ public interface Fruit { /* * 采集方法 */ public void get(); }水果工厂:
package SimpleFactory; /** * 类说明 * * <pre> * Modify Information: * Author Date Description * ============ =========== ============================ * DELL 2017年2月4日 Create this file * </pre> * */ public class FruitFactory { /* * 获得Apple实例 */ public static Fruit getApple() { return new Apple(); } public static Fruit getBanana() { return new Banana(); } public static Fruit getFruit(String type) throws InstantiationException, IllegalAccessException, ClassNotFoundException { // if (type.equalsIgnoreCase("apple")) { // return Apple.class.newInstance(); // } else if (type.equalsIgnoreCase("banana")) { // return Banana.class.newInstance(); // } else { // System.out.println("找不到对应都实体类"); // } // return null; Class fruit = Class.forName(type); return (Fruit)fruit.newInstance(); } }测试类:
package SimpleFactory; /** * 类说明 * * <pre> * Modify Information: * Author Date Description * ============ =========== ============================ * DELL 2017年2月4日 Create this file * </pre> * */ public class MainClass { /* * 多态的形式 接口进行引用 */ public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException { /* Fruit apple = new Apple(); Fruit banana = new Banana(); apple.get(); banana.get();*/ /* * 简单工厂方法 * 可以根据工厂去创建自己需要的产品 * 下面都getFruit 就是生产水果产品用的,但是在某种程度上是不好的,增加一个产品就要增加getFruit方法 */ /* Fruit apple = new FruitFactory().getApple(); Fruit banana = new FruitFactory().getBanana();*/ // Fruit apple = FruitFactory.getApple(); // Fruit banana = FruitFactory.getBanana(); // Fruit apple = FruitFactory.getFruit("apple"); // apple.get(); // Fruit apple = FruitFactory.getFruit("Test.SimpleFactory.Apple"); // apple.get(); } }
wangxiaoming 认证博客专家 架构 Spring Boot Redis 博客是很好的总结和记录工具,如果有问题,来不及回复,关注微信公众号:程序员开发者社区,获取我的联系方式,向我提问,也可以给我发送邮件,联系 1275801617@qq.com
