1、以一个获取交通工具然后去上班的例子来说明,首先,创建Car接口。package com.boxun;/** * 车接口 * Created by kstrive on 2017/5/5. */public interface Car { /** * 上班函数 */ void gotoWork();}
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("骑自行车去上班!"); }}
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("坐公交车去上班!"); }}
4、下面创建车的工厂接口,它有一个方法就是获取交通工具getCar(),返回Car对象:package com.boxun;/** * 车工厂接口 * Created by kstrive on 2017/5/5. */public interface ICarFactory { /** * 获取交通工具 * * @return */ Car getCar();}
5、创建自行车工厂类,实现车工厂接口,并在getCar方法返回Bike对象:package 罕铞泱殳com.boxu荏鱿胫协n;/** * 自行车工厂 * Created by kstrive on 2017/5/5. */public class BikeFactory implements ICarFactory { @Override public Car getCar() { return new Bike(); }}
6、创建公共汽车(公交车)类,也是实现车工厂接口,并在getCar方法返回Bus对象:pac氯短赤亻kage com.boxun;/忮氽阝另** * 公共汽车工厂类 * Created by kstrive on 2017/5/5. */public class BusFactory implements ICarFactory { @Override public Car getCar() { return new Bus(); }}
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(); }}