web123456

Design Pattern-Difference between Factory Pattern and Strategy Pattern

Factory modelBoth the strategy pattern are important in the design patternComponents, They are used to solve different types of software design problems. Here are the differences between them:

  1. Different purposes

    • Factory modelThe main purpose of (Factory Pattern) is to create objects. It provides an interface for creating objects so that subclasses can decide which class to instantiate. The focus of the factory model is on how to create and manage objects.
    • Policy Mode(Strategy Pattern) aims to define a series of algorithms, encapsulate each algorithm and make them interchangeable. The policy pattern allows the algorithm to change without affecting the client. Its focus is on how to use different methods or algorithms to accomplish a certain behavior.
  2. Use scenarios

    • Factory modelCommonly used when we need to dynamically decide which instance of the class to create at runtime, and these classes have common interfaces or base classes.
    • Policy ModeSuitable for use when a behavior or algorithm that requires dynamically changing an object, and these behaviors can be replaced with each other.
  3. Different roles

    • Factory modelIncludes factory interfaces (or abstract classes) and concrete factory classes, which are responsible for creating product objects.
    • Policy ModeContains policy interfaces and specific policy implementations, and uses these policies in context classes.
  4. Design Intent

    • Factory modelThe complexity and specific implementation of creating objects are hidden. The client only needs to obtain the required objects through the factory, without knowing the object creation process.
    • Policy ModeAllow clients to select algorithms in the same family of algorithms to ensure that changes in algorithms do not affect customers using algorithms.

Scene: Suppose we have an application that needs to create various types of documents in different ways, such asWorddocument,PDFdocument,Exceldocument. Each document type has a different creation implementation.

Implement factory model

  1. Document interface: Define a common interface or abstract class to represent a document.

    java

    1. interface Document {
    2. void open();
    3. }

    Open in:Code Editor

  2. Specific document categories: Different classes that implement document interfaces.

    java

    1. class WordDocument implements Document {
    2. public void open() {
    3. System.out.println("Opening a Word document.");
    4. }
    5. }
    6. class PdfDocument implements Document {
    7. public void open() {
    8. System.out.println("Opening a PDF document.");
    9. }
    10. }

    Open in:Code Editor

  3. Factory: Provides a unified interface for document creation through factory classes.

    java

    1. class DocumentFactory {
    2. public Document createDocument(String type) {
    3. if (type.equalsIgnoreCase("Word")) {
    4. return new WordDocument();
    5. } else if (type.equalsIgnoreCase("PDF")) {
    6. return new PdfDocument();
    7. } else {
    8. throw new IllegalArgumentException("Unknown document type");
    9. }
    10. }
    11. }

    Open in:Code Editor

  4. Use factory

    java

    1. public class Main {
    2. public static void main(String[] args) {
    3. DocumentFactory factory = new DocumentFactory();
    4. Document doc = factory.createDocument("Word");
    5. doc.open(); // Output: Opening a Word document.
    6. }
    7. }

    Open in:Code Editor

Policy ModeCase

Scene: Suppose we have an application responsible for processing different types of payments. We need to support a variety of payment strategies, such as credit card payment, Alipay payment and WeChat payment.

Implementing the policy model

  1. Payment policy interface: Define a common interface to represent payment policy.

    java

    1. interface PaymentStrategy {
    2. void pay(int amount);
    3. }

    Open in:Code Editor

  2. Specific strategy category: Implement different types of payment policy interfaces.

    java

    1. class CreditCardPayment implements PaymentStrategy {
    2. public void pay(int amount) {
    3. System.out.println("Paying " + amount + " using Credit Card.");
    4. }
    5. }
    6. class AlipayPayment implements PaymentStrategy {
    7. public void pay(int amount) {
    8. System.out.println("Paying " + amount + " using Alipay.");
    9. }
    10. }

    Open in:Code Editor

  3. Context Class: Use policy interfaces in context class.

    java

    1. class PaymentContext {
    2. private PaymentStrategy strategy;
    3. public PaymentContext(PaymentStrategy strategy) {
    4. this.strategy = strategy;
    5. }
    6. public void executePayment(int amount) {
    7. (amount);
    8. }
    9. }

    Open in:Code Editor

  4. Usage strategies

    java

    1. public class Main {
    2. public static void main(String[] args) {
    3. PaymentContext context = new PaymentContext(new CreditCardPayment());
    4. (100); // Output: Paying 100 using Credit Card.
    5. context = new PaymentContext(new AlipayPayment());
    6. (200); // Output: Paying 200 using Alipay.
    7. }
    8. }

    Open in:Code Editor

Summary of the difference

The factory model focuses on the creation process, while the policy model focuses on changes in behavior or algorithms. They can be used alone in different designs or combined to achieve more complex functions.

  • Factory model: Transfer the responsibility for instantiating an object to the factory by creating a factory class. When we don't know which class we need to instantiate, the factory pattern is used. It hides the complexity of object instantiation.

  • Policy Mode: Allows the selection of different algorithms or operations during execution. When we need to dynamically change the behavior or algorithm of an object, we use the policy pattern. This allows the algorithm to vary independently of the client using it.