登录
首页 >  文章 >  java教程

理解工厂方法模式

时间:2025-01-14 13:57:31 143浏览 收藏

文章小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《理解工厂方法模式》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


理解工厂方法模式

工厂方法模式详解

本文将深入探讨工厂方法模式,一种在实际应用中广泛使用的高效设计模式。文中如有任何错误,欢迎指出,我将及时更正。

工厂方法模式的核心在于定义一个用于创建对象的接口,但允许子类决定实例化哪个具体的类。

问题场景

假设您正在开发一个银行转账应用,需要支持多种转账方式,例如银行转账和PayPal转账。

在未应用工厂方法模式之前,代码可能存在以下问题:

首先,我们来看一个Java示例。场景:用户A向用户B转账(通过银行转账或PayPal)。

项目结构:

problem/
├─ BankApp.java
├─ service/
│  ├─ PaypalTransferPayment.java
│  ├─ BankTransferPayment.java
├─ data/
│  ├─ Person.java

主程序创建两个用户对象,并设定初始金额:

package problem;

import problem.data.Person;

public class BankApp {
    public static void main(String[] args) {
        Person person1 = new Person("John", 1000);
        Person person2 = new Person("Jane", 500);
    }
}

分别实现银行转账和PayPal转账类:

package problem.service;

import problem.data.Person;

public class BankTransferPayment {
    public void processPayment(Person fromAccount, Person toAccount, float amount) {
        fromAccount.withdraw(amount);
        toAccount.deposit(amount);
        System.out.println("Bank transfer payment success.");
    }
}
package problem.service;

import problem.data.Person;

public class PaypalPayment {
    public void processPayment(Person fromAccount, Person toAccount, float amount) {
        fromAccount.withdraw(amount);
        toAccount.deposit(amount);
        System.out.println("Paypal transfer payment success.");
    }
}

在主函数中添加转账逻辑:

package problem;

import problem.data.Person;
import problem.service.BankTransferPayment;
import problem.service.PaypalPayment;

public class BankApp {
    public static void main(String[] args) {
        Person person1 = new Person("John", 1000);
        Person person2 = new Person("Jane", 500);

        String paymentMethod = "bank_transfer";

        if (paymentMethod.equals("bank_transfer")) {
            BankTransferPayment bankTransferPayment = new BankTransferPayment();
            bankTransferPayment.processPayment(person1, person2, 100);

            System.out.println("===Method bank_transfer===");
            System.out.println(person1.getName() + " has " + person1.getAmount());
            System.out.println(person2.getName() + " has " + person2.getAmount());
        } else if (paymentMethod.equals("paypal")) {
            PaypalPayment paypalPayment = new PaypalPayment();
            paypalPayment.processPayment(person1, person2, 100);

            System.out.println("===Method paypal===");
            System.out.println(person1.getName() + " has " + person1.getAmount());
            System.out.println(person2.getName() + " has " + person2.getAmount());
        }
    }
}

现有方案的问题:

  1. 代码冗余: processPayment 方法在不同支付方式中重复。
  2. 耦合度高: 应用程序直接创建支付方式对象,扩展性差。
  3. 可扩展性差: 添加新的支付方式需要修改源代码。

解决方案:工厂方法模式

为了解决上述问题,我们将采用工厂方法模式。

项目结构(解决方案):

solution/
├─ BankApp.java
├─ service/
│  ├─ payments/
│  │  ├─ Payment.java
│  │  ├─ PaymentFactory.java
│  │  ├─ BankTransferPayment.java
│  │  ├─ PaypalTransferPayment.java
├─ data/
│  ├─ Person.java

步骤一:创建 Payment 接口,定义 processPayment 方法:

package solution.service.payments;

import solution.data.Person;

public interface Payment {
    void processPayment(Person fromAccount, Person toAccount, float amount);
}

步骤二:BankTransferPaymentPaypalPayment 类实现 Payment 接口:

package solution.service.payments;

import solution.data.Person;

public class BankTransferPayment implements Payment {
    @Override
    public void processPayment(Person fromAccount, Person toAccount, float amount) {
        fromAccount.withdraw(amount);
        toAccount.deposit(amount);
        System.out.println("Bank transfer payment success.");
    }
}
package solution.service.payments;

import solution.data.Person;

public class PaypalPayment implements Payment {
    @Override
    public void processPayment(Person fromAccount, Person toAccount, float amount) {
        fromAccount.withdraw(amount);
        toAccount.deposit(amount);
        System.out.println("Paypal transfer payment success.");
    }
}

步骤三:创建 PaymentFactory 类,根据支付类型创建对应的支付对象:

package solution.service.payments;

public class PaymentFactory {
    public Payment createPayment(String paymentType) {
        if (paymentType == null) {
            return null;
        }
        if (paymentType.equalsIgnoreCase("bank_transfer")) {
            return new BankTransferPayment();
        } else if (paymentType.equalsIgnoreCase("paypal")) {
            return new PaypalPayment();
        }
        return null;
    }
}

步骤四:在主程序中使用工厂:

修改主函数,使用工厂方法模式:

package solution;

import solution.data.Person;
import solution.service.payments.Payment;
import solution.service.payments.PaymentFactory;

public class BankApp {
    public static void main(String[] args) {
        Person person1 = new Person("John", 1000);
        Person person2 = new Person("Jane", 500);

        String paymentMethod = "paypal";

        Payment payment = new PaymentFactory().createPayment(paymentMethod);
        payment.processPayment(person1, person2, 100);
    }
}

工厂方法模式的优势

  • 代码更简洁: 消除了冗余代码。
  • 降低耦合度: 对象创建委托给工厂,提高了可维护性。
  • 增强可扩展性: 添加新的支付方式无需修改原有代码,只需创建新的支付类和注册到工厂即可。

改进:策略模式结合工厂方法模式 (开闭原则)

为了进一步提高可扩展性,并遵循开闭原则,我们可以结合策略模式,实现动态注册支付方式。

修改 PaymentFactory.java

package solution.service.payments;

import java.util.HashMap;
import java.util.Map;

public class PaymentFactory {
    private Map<String, Payment> paymentMap;

    public PaymentFactory() {
        this.paymentMap = new HashMap<>();
    }

    public Payment createPayment(String paymentType) {
        return paymentMap.get(paymentType);
    }

    public void registerPayment(String paymentType, Payment payment) {
        paymentMap.put(paymentType, payment);
    }

    public PaymentFactory initializePaymentMethods() {
        Payment bankTransferPayment = new BankTransferPayment();
        Payment paypalPayment = new PaypalPayment();

        this.registerPayment("bank_transfer", bankTransferPayment);
        this.registerPayment("paypal", paypalPayment);

        return this;
    }
}

修改主程序:

package solution;

import solution.data.Person;
import solution.service.payments.Payment;
import solution.service.payments.PaymentFactory;

public class BankApp {
    public static void main(String[] args) {
        Person person1 = new Person("John", 1000);
        Person person2 = new Person("Jane", 500);

        String paymentMethod = "BANK_TRANSFER";

        Payment payment = new PaymentFactory()
                .initializePaymentMethods()
                .createPayment(paymentMethod);
        payment.processPayment(person1, person2, 100);
    }
}

通过这种方式,添加新的支付方式只需创建新的类并注册到工厂即可,无需修改工厂本身的代码,完美遵循开闭原则。

希望本文对您理解和应用工厂方法模式有所帮助。

参考资料:

设计模式大全

终于介绍完啦!小伙伴们,这篇关于《理解工厂方法模式》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布文章相关知识,快来关注吧!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>