设计模式学习(二):接口的作用1-动态加载实例-简单工厂模式

来源:互联网 发布:sql server分离mdf 编辑:程序博客网 时间:2024/03/29 16:59
接口:import java.lang.*;public interface Common ...{    double runTimer(double a, double b, double c);}实现类1:public class Plane implements Common ...{    public double runTimer(double a, double b, double c) ...{        return (a+ b + c);    }}实现类2:public class Car implements Common ...{    public double runTimer(double a, double b, double c) ...{        return ( a*b/c );    }}主类:public class ComputeTime ...{    public static void main(String args[]) ...{    try ...{            Common d=(Common) Class.forName(args[0]).newInstance();        这个地方通过一个类名来确定是具体哪一个实现类,当更换了实现类时,只要传一个类名过来就行,这里的代码不用修改,这就是接口的好处,            有人要问既然知道类名了直接new一个它的实例不就完了,那样的话就要修改这里的代码了,耦合性不就大了。            其实把“Common d=(Common) Class.forName(args[0]).newInstance();”封装到一个类里(工厂类)就成了简单工厂模式!            v=d.runTimer(A,B,C);            t=1000/v;            System.out.println("平均速度: "+v+" km/h");            System.out.println("运行时间:"+t+" 小时");        } catch(Exception e) ...{            System.out.println("class not found");        }    }}

0 0