策略模式和工厂模式在设计上有哪些相似之处和不同之处?请通过实例对比说明。

策略模式和工厂模式是两种常用的设计模式,它们在某些设计目标上有相似之处,但也有明显的区别。以下是它们的对比说明:

相似之处

  1. 封装变化的方向 策略模式和工厂模式都通过封装变化的部分来提升代码的灵活性和可维护性。策略模式封装的是算法的变化,而工厂模式封装的是对象创建的变化。

  2. 依赖抽象而非实现 两种模式都遵循了依赖倒置原则(DIP),通过抽象(接口或抽象类)来隔离具体实现,从而减少耦合。

不同之处

  1. 目的不同

    • 策略模式:主要用于动态替换算法或行为。客户端可以根据需求选择不同的策略。
    • 工厂模式:主要用于创建对象的实例,隐藏对象的创建细节。
  2. 适用场景不同

    • 策略模式:适用于需要根据不同条件动态切换算法的场景,例如支付方式的选择(支付宝、微信支付)。
    • 工厂模式:适用于需要统一管理对象创建的复杂场景,例如数据库连接池的创建。
  3. 客户端调用方式不同

    • 策略模式:客户端通常直接使用策略接口调用具体策略。
    • 工厂模式:客户端通过工厂类获取对象实例,无需关心具体的创建逻辑。

实例对比

策略模式示例

以下是一个支付策略的实现:

// 策略接口
interface PaymentStrategy {
    void pay(int amount);
}

// 具体策略:支付宝支付
class AlipayStrategy implements PaymentStrategy {
    @Override
    public void pay(int amount) {
        System.out.println("使用支付宝支付:" + amount + "元");
    }
}

// 具体策略:微信支付
class WechatPayStrategy implements PaymentStrategy {
    @Override
    public void pay(int amount) {
        System.out.println("使用微信支付:" + amount + "元");
    }
}

// 上下文类
class PaymentContext {
    private PaymentStrategy strategy;

    public PaymentContext(PaymentStrategy strategy) {
        this.strategy = strategy;
    }

    public void executePayment(int amount) {
        strategy.pay(amount);
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        PaymentStrategy alipay = new AlipayStrategy();
        PaymentContext context = new PaymentContext(alipay);
        context.executePayment(100);
    }
}

工厂模式示例

以下是一个数据库连接工厂的实现:

// 产品接口
interface Connection {
    void connect();
}

// 具体产品:MySQL 连接
class MySQLConnection implements Connection {
    @Override
    public void connect() {
        System.out.println("连接到 MySQL 数据库");
    }
}

// 具体产品:PostgreSQL 连接
class PostgreSQLConnection implements Connection {
    @Override
    public void connect() {
        System.out.println("连接到 PostgreSQL 数据库");
    }
}

// 工厂类
class ConnectionFactory {
    public static Connection createConnection(String type) {
        switch (type) {
            case "MySQL":
                return new MySQLConnection();
            case "PostgreSQL":
                return new PostgreSQLConnection();
            default:
                throw new IllegalArgumentException("未知的数据库类型");
        }
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        Connection connection = ConnectionFactory.createConnection("MySQL");
        connection.connect();
    }
}

总结

  • 策略模式更注重行为的动态替换,客户端可以根据需求选择不同的策略。
  • 工厂模式更注重对象的创建过程,客户端无需关心对象的创建细节。
  • 两种模式结合使用时,可以进一步解耦代码,例如在策略模式中使用工厂模式创建策略对象。