java 工厂方法模式

2025-10-29 02:04:35

1、以一个获取交通工具然后去上班的例子来说明,首先,创建Car接口。

package com.boxun;/** * 车接口 * Created by kstrive on 2017/5/5. */public interface Car {    /**     * 上班函数     */    void gotoWork();}

java 工厂方法模式

2、创建自行车类,Bike实现Car接口:

package com.boxun;/** * 自行车 * Created by kstrive on 2017/5/5. */public class Bike implements Car{    @Override    public void gotoWork() {        System.out.println("骑自行车去上班!");    }}

java 工厂方法模式

3、创建公共汽车类,Bus实现Car接口:

package com.boxun;/** * 公交车 * Created by kstrive on 2017/5/5. */public class Bus implements Car {    @Override    public void gotoWork() {        System.out.println("坐公交车去上班!");    }}

java 工厂方法模式

4、下面创建车的工厂接口,它有一个方法就是获取交通工具getCar(),返回Car对象:

package com.boxun;/** * 车工厂接口 * Created by kstrive on 2017/5/5. */public interface ICarFactory {    /**     * 获取交通工具     *     * @return     */    Car getCar();}

java 工厂方法模式

5、创建自行车工厂类,实现车工厂接口,并在getCar方法返回Bike对象:

package com.boxun;/** * 自行车工厂 * Created by kstrive on 2017/5/5. */public class BikeFactory implements ICarFactory {    @Override    public Car getCar() {        return new Bike();    }}

java 工厂方法模式

6、创建公共汽车(公交车)类,也是实现车工厂接口,并在getCar方法返回Bus对象:

package com.boxun;/** * 公共汽车工厂类 * Created by kstrive on 2017/5/5. */public class BusFactory implements ICarFactory {    @Override    public Car getCar() {        return new Bus();    }}

java 工厂方法模式

7、最后,我们写一个测试类来测试验证我们的工厂方法,如图,可见输出结果,如我们所设计:

package com.boxun;/** * 测试类 * Created by kstrive on 2017/5/5. */public class TestFactory {    public static void main(String[] args) {        TestFactory tf = new TestFactory();        tf.test();;    }    public void test() {        ICarFactory factory = null;        // bike        factory = new BikeFactory();        Car bike = factory.getCar();        bike.gotoWork();        // bus        factory = new BusFactory();        Car bus = factory.getCar();        bus.gotoWork();    }}

java 工厂方法模式

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢