一、抽象工厂是工厂方法模式的进一步升级,它消除了对象创建过程中的与不同工厂类的耦合
二、示例代码
1.定义抽象类
package cn.edu.tju.app; //定义交通工具抽象类 public abstract class Vehicle { //定义"启动"抽象方法 public abstract void start(); }
2.定义上述抽象类的2个实现类
package cn.edu.tju.app; public class Car extends Vehicle { @Override public void start() { System.out.println("开动汽车"); } }
package cn.edu.tju.app; public class Plane extends Vehicle { @Override public void start() { System.out.println("开动飞机"); } }
3.定义抽象工厂类:
package cn.edu.tju.app; public abstract class VehicleAbstractFactory { public abstract Vehicle getVehicle(); }
4.定义两个具体工厂类分别实现步骤3中定义的抽象工厂类:
package cn.edu.tju.app; public class CarConcreteFactory extends VehicleAbstractFactory { @Override public Vehicle getVehicle() { return new Car(); } }
package cn.edu.tju.app; public class PlaneConcreteFactory extends VehicleAbstractFactory { @Override public Vehicle getVehicle() { return new Plane(); } }
5.定义主类,分别调用抽象工厂类的方法:
package cn.edu.tju.app; public class AbstractFactoryTest { public static void main(String[] args) { VehicleAbstractFactory vehicleAbstractFactory=new CarConcreteFactory(); Vehicle vehicle = vehicleAbstractFactory.getVehicle(); vehicle.start(); VehicleAbstractFactory vehicleAbstractFactory2=new PlaneConcreteFactory(); Vehicle vehicle2 = vehicleAbstractFactory2.getVehicle(); vehicle2.start(); } }
6.程序输出:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)