设计模式-创建型-工厂模式

时间:2024-11-24 07:07:03
// 抽象产品类 interface Vehicle { void drive(); } // 具体产品类:汽车 class Car implements Vehicle { @Override public void drive() { System.out.println("Driving a car."); } } // 具体产品类:自行车 class Bicycle implements Vehicle { @Override public void drive() { System.out.println("Riding a bicycle."); } } // 工厂类 class VehicleFactory { // 根据类型创建对应的交通工具对象 public static Vehicle createVehicle(String type) { if (type.equals("car")) { return new Car(); } else if (type.equals("bicycle")) { return new Bicycle(); } else { throw new IllegalArgumentException("Unknown vehicle type: " + type); } } } // 客户端代码 public class FactoryPatternDemo { public static void main(String[] args) { Vehicle car = VehicleFactory.createVehicle("car"); car.drive(); Vehicle bicycle = VehicleFactory.createVehicle("bicycle"); bicycle.drive(); } }