zoukankan      html  css  js  c++  java
  • 利用反射机制实现工厂设计模式的高扩展性

    直接看代码了:

    复制代码
    interface Fruit{    
    public void grow();
    public void eat();
    }
    class Apple implements Fruit{
    public void grow(){
    System.out.println("苹果在生长...");
    }
    public void eat(){
    System.out.println("吃苹果...");
    }
    }
    class Orange implements Fruit{
    public void grow(){
    System.out.println("橘子在生长...");
    }
    public void eat(){
    System.out.println("吃橘子...");
    }
    }
    class Banana implements Fruit{
    public void grow(){
    System.out.println("香蕉在生长...");
    }
    public void eat(){
    System.out.println("吃香蕉...");
    }
    }
    class Factory{
    public static Fruit getFruit(String className){
    Fruit f = null;
    try{
    f = (Fruit)Class.forName(className).newInstance();
    }catch (Exception e){}
    return f;
    }
    }
    public class Demo07{
    public static void main(String args[]){
    Fruit f = Factory.getFruit("Banana");
    f.grow();
    }
    }
    复制代码

      实际中是通过配置fruit.xml文件来保持包.类名称的此种代码是典型的配置与程序相分离,程序直接有配置文件有关。某一个部分的修改不影响其他程序。

  • 相关阅读:
    自定义文书思路
    传输
    Netty的组件和设计
    第一款Netty应用程序
    Netty异步和事件驱动
    初识MQTT
    TCP/IP协议分层模型
    uni原生插件的开发(安卓)
    uniapp离线打包记录
    日常问题处理:Linux通过设备名称如何查看硬盘SN
  • 原文地址:https://www.cnblogs.com/makeryan/p/2498273.html
Copyright © 2011-2022 走看看