工厂模式和策略模式的区别

工厂模式和策略模式是两种不同的设计模式

一、目的和用途
  1. 工厂模式(用于创建对象,将对象的创建和使用分离):

    • 目的是创建对象,将对象的创建和使用分离。它提供了一种创建对象的方式,使得客户端代码不需要直接实例化具体的类,而是通过工厂类来创建对象。

    • 常用于创建复杂对象或根据不同的条件创建不同类型的对象,提高代码的可维护性和可扩展性。

  2. 策略模式(主要用于封装算法或行为,使得不同算法或行为可以相互替换):

    • 目的是封装一系列的算法或行为,使得这些算法或行为可以相互替换。它将算法的选择和实现分离,使得客户端代码可以在运行时根据需要选择不同的算法。

    • 常用于实现多种不同的算法或行为,并且这些算法或行为可以根据不同的情况进行切换。

二、结构和实现方式
  1. 工厂模式:
    • 通常包含一个工厂类和多个具体产品类。工厂类负责创建具体产品类的实例,客户端代码只与工厂类交互,而不直接与具体产品类交互。
    • 工厂类可以是简单工厂、工厂方法或抽象工厂,具体实现方式根据实际需求而定。
  2. 策略模式:
    • 通常包含一个策略接口和多个具体策略实现类,以及一个环境类。策略接口定义了算法的公共接口,具体策略实现类实现了策略接口,环境类持有一个策略对象,并在运行时根据需要选择不同的策略。
    • 客户端代码通过环境类来使用策略,而环境类可以在运行时根据需要动态地切换策略。
三、代码示例
  1. 工厂模式示例:
    • 假设我们有一个图形绘制的应用程序,需要根据用户的选择绘制不同类型的图形,如圆形、矩形和三角形。我们可以使用工厂模式来创建这些图形对象。
    • 定义一个图形接口:
java 复制代码
     public interface Shape {
         void draw();
     }
  • 实现具体的图形类:
java 复制代码
     public class Circle implements Shape {
         @Override
         public void draw() {
             System.out.println("Drawing a circle.");
         }
     }

     public class Rectangle implements Shape {
         @Override
         public void draw() {
             System.out.println("Drawing a rectangle.");
         }
     }

     public class Triangle implements Shape {
         @Override
         public void draw() {
             System.out.println("Drawing a triangle.");
         }
     }
  • 创建一个图形工厂类:
java 复制代码
     public class ShapeFactory {
         public static Shape createShape(String shapeType) {
             if (shapeType.equalsIgnoreCase("circle")) {
                 return new Circle();
             } else if (shapeType.equalsIgnoreCase("rectangle")) {
                 return new Rectangle();
             } else if (shapeType.equalsIgnoreCase("triangle")) {
                 return new Triangle();
             } else {
                 return null;
             }
         }
     }
  • 客户端代码可以使用工厂类来创建图形对象:
java 复制代码
     public class Client {
         public static void main(String[] args) {
             Shape shape1 = ShapeFactory.createShape("circle");
             shape1.draw();

             Shape shape2 = ShapeFactory.createShape("rectangle");
             shape2.draw();

             Shape shape3 = ShapeFactory.createShape("triangle");
             shape3.draw();
         }
     }
  1. 策略模式示例:
    • 假设我们有一个排序算法的应用程序,需要根据用户的选择使用不同的排序算法,如冒泡排序、快速排序和插入排序。我们可以使用策略模式来实现这些排序算法。
    • 定义一个排序策略接口:
java 复制代码
     public interface SortingStrategy {
         void sort(int[] array);
     }
  • 实现具体的排序策略类:
java 复制代码
     public class BubbleSort implements SortingStrategy {
         @Override
         public void sort(int[] array) {
             int n = array.length;
             for (int i = 0; i < n - 1; i++) {
                 for (int j = 0; j < n - i - 1; j++) {
                     if (array[j] > array[j + 1]) {
                         // 交换元素
                         int temp = array[j];
                         array[j] = array[j + 1];
                         array[j + 1] = temp;
                     }
                 }
             }
         }
     }

     public class QuickSort implements SortingStrategy {
         @Override
         public void sort(int[] array) {
             quickSort(array, 0, array.length - 1);
         }

         private void quickSort(int[] array, int low, int high) {
             if (low < high) {
                 int pivotIndex = partition(array, low, high);
                 quickSort(array, low, pivotIndex - 1);
                 quickSort(array, pivotIndex + 1, high);
             }
         }

         private int partition(int[] array, int low, int high) {
             int pivot = array[high];
             int i = low - 1;
             for (int j = low; j < high; j++) {
                 if (array[j] < pivot) {
                     i++;
                     // 交换元素
                     int temp = array[i];
                     array[i] = array[j];
                     array[j] = temp;
                 }
             }
             // 交换元素
             int temp = array[i + 1];
             array[i + 1] = array[high];
             array[high] = temp;
             return i + 1;
         }
     }

     public class InsertionSort implements SortingStrategy {
         @Override
         public void sort(int[] array) {
             int n = array.length;
             for (int i = 1; i < n; i++) {
                 int key = array[i];
                 int j = i - 1;
                 while (j >= 0 && array[j] > key) {
                     array[j + 1] = array[j];
                     j--;
                 }
                 array[j + 1] = key;
             }
         }
     }
  • 创建一个环境类,用于持有排序策略对象并调用排序算法:
java 复制代码
     public class Sorter {
         private SortingStrategy sortingStrategy;

         public Sorter(SortingStrategy sortingStrategy) {
             this.sortingStrategy = sortingStrategy;
         }

         public void setSortingStrategy(SortingStrategy sortingStrategy) {
             this.sortingStrategy = sortingStrategy;
         }

         public void sortArray(int[] array) {
             sortingStrategy.sort(array);
         }
     }
  • 客户端代码可以使用环境类来选择不同的排序策略:
java 复制代码
     public class Client {
         public static void main(String[] args) {
             int[] array1 = {5, 3, 8, 4, 2};
             Sorter sorter1 = new Sorter(new BubbleSort());
             sorter1.sortArray(array1);
             print("Bubble Sort: ");
             for (int num : array1) {
                 System.out.print(num + " ");
             }
             System.out.println();

             int[] array2 = {9, 7, 6, 1, 3};
             Sorter sorter2 = new Sorter(new QuickSort());
             sorter2.sortArray(array2);
             print("Quick Sort: ");
             for (int num : array2) {
                 System.out.print(num + " ");
             }
             System.out.println();

             int[] array3 = {4, 2, 7, 1, 8};
             Sorter sorter3 = new Sorter(new InsertionSort());
             sorter3.sortArray(array3);
             print("Insertion Sort: ");
             for (int num : array3) {
                 System.out.print(num + " ");
             }
             System.out.println();
         }
     }
相关推荐
白总Server34 分钟前
rust解说
linux·开发语言·后端·golang·rust·debian·php
金庆35 分钟前
Rust Pin
开发语言·后端·rust
Lill_bin1 小时前
CAS机制:并发编程中的原子操作
java·服务器·开发语言·windows·算法·微服务
wh233z1 小时前
Codeforces Round 969 (Div. 2) (A~D)
c语言·开发语言·数据结构·c++·算法·图论
曼亿点1 小时前
python的流程控制语句之制作空气质量评估系统
android·开发语言·python
碎像1 小时前
EasyExcel 快速入门
java·spring boot·easyexcel
weixin_586062022 小时前
PHP 环境搭建教程
开发语言·php
Damon小智2 小时前
SpringBoot权限认证-Sa-Token的使用与详解
java·spring boot·spring cloud·微服务·sa-token
祁思妙想2 小时前
《JavaEE进阶》----16.<Mybatis简介、操作步骤、相关配置>
java·java-ee·mybatis
程序猿大波2 小时前
基于Java、SpringBoot、Vue的加油站管理系统设计
java·vue.js·spring boot