随笔-28  评论-15  文章-81  trackbacks-0
 

package com.tanm.factoryDemo;

interface Car {

    public void run();

    public void stop();

}

class Benz implements Car {

    public void run() {

       System.out.println("Benz开始启动了");

    }

    public void stop() {

       System.out.println("Benz停车了");

    }

}

class Toyota implements Car {

    public void run() {

       System.out.println("Toyota启动了");

    }

    public void stop() {

       System.out.println("Toyota停车了");

    }

}

class Ford implements Car {

    public void run() {

       System.out.println("Ford开始启动了");

    }

    public void stop() {

       System.out.println("Ford停车了");

    }

}

class Factory {

    public static Car getCarInstance(String type) {

       Car c = null;

       try {

           // 利用java的反射机制

           c = (Car) Class.forName("com.tanm.factoryDemo." + type)

                  .newInstance();

       } catch (InstantiationException e) {

           e.printStackTrace();

       } catch (IllegalAccessException e) {

           e.printStackTrace();

       } catch (ClassNotFoundException e) {

           e.printStackTrace();

       }

       return c;

    }

}

public class FactoryDemo {

    public static void main(String[] args) {

       Car c = Factory.getCarInstance("Toyota");

       if (c != null) {

           c.run();

           c.stop();

       } else {

           System.out.println("造不了这种汽车");

       }

    }

}

posted on 2007-10-16 17:39 谭明 阅读(309) 评论(0)  编辑  收藏 所属分类: Java设计模式

只有注册用户登录后才能发表评论。


网站导航: