【设计模式】Java 设计模式之工厂模式(Factory Pattern)
    		       		warning:
    		            这篇文章距离上次修改已过435天,其中的内容可能已经有所变动。
    		        
        		                
                
// 定义一个简单的接口
interface Car {
    void drive();
}
 
// 实现这个接口的具体类
class TeslaCar implements Car {
    public void drive() {
        System.out.println("Tesla is driving.");
    }
}
 
class BMWCar implements Car {
    public void drive() {
        System.out.println("BMW is driving.");
    }
}
 
// 定义一个简单的工厂类
class CarFactory {
    public static Car createCar(String type) {
        if ("Tesla".equals(type)) {
            return new TeslaCar();
        } else if ("BMW".equals(type)) {
            return new BMWCar();
        } else {
            return null;
        }
    }
}
 
// 使用工厂类创建对象
public class FactoryPatternExample {
    public static void main(String[] args) {
        Car tesla = CarFactory.createCar("Tesla");
        if (tesla != null) {
            tesla.drive();
        }
 
        Car bmw = CarFactory.createCar("BMW");
        if (bmw != null) {
            bmw.drive();
        }
    }
}这个简单的代码示例展示了如何使用工厂模式来创建对象。CarFactory 类提供了一个静态方法 createCar,根据传入的字符串类型来创建相应的车辆对象。在 main 方法中,我们通过调用 CarFactory.createCar 方法来获取车辆实例,并调用它们的 drive 方法。这个例子简单直观地展示了工厂模式的用法。
评论已关闭