设计模式-工厂模式和策略模式

工厂模式(Factory Pattern)和策略模式(Strategy Pattern)是两种常见的设计模式,它们在目的和使用场景上有显著的区别。

一:工厂模式

目的:工厂模式的主要目的是创建对象。它通过定义一个创建对象的接口,让子类决定实例化哪一个类。工厂模式使得一个类的实例化延迟到其子类。

使用场景:

  • 需要创建复杂对象,且具体的类在代码中可能会频繁变化。
  • 系统不应依赖于产品类实例如何被创建、组合和表达的细节。

假设我们有一个应用程序需要支持多种类型的日志记录(如文件日志、数据库日志、控制台日志等)。我们可以使用工厂模式来创建不同类型的日志记录器。

// 日志记录器接口

interface Logger {

void log(String message);

}

// 文件日志记录器

class FileLogger implements Logger {

@Override

public void log(String message) {

System.out.println("Logging to a file: " + message);

}

}

// 数据库日志记录器

class DatabaseLogger implements Logger {

@Override

public void log(String message) {

System.out.println("Logging to a database: " + message);

}

}

// 日志工厂

class LoggerFactory {

public static Logger getLogger(String loggerType) {

if ("file".equalsIgnoreCase(loggerType)) {

return new FileLogger();

} else if ("database".equalsIgnoreCase(loggerType)) {

return new DatabaseLogger();

} else {

throw new IllegalArgumentException("Unknown logger type");

}

}

}

// 使用工厂模式创建日志记录器

public class FactoryPatternExample {

public static void main(String\[\] args) {

Logger logger = LoggerFactory.getLogger("file");

logger.log("This is a log message.");

}

}

二:策略模式

目的:策略模式的主要目的是定义一系列算法,将每一个算法封装起来,并让它们可以互换。策略模式使得算法可以独立于使用它的客户端变化。

使用场景:

  • 需要在运行时选择不同的算法。
  • 需要在不同的情境下使用不同的业务规则。
  • 避免使用条件语句来选择不同的行为。

例子: 假设我们有一个应用程序需要对一组数字进行排序,但排序算法可能会根据用户的选择而变化。我

import java.util.Arrays;

// 排序策略接口

interface SortStrategy {

void sort(int\[\] data);

}

// 快速排序策略

class QuickSortStrategy implements SortStrategy {

@Override

public void sort(int\[\] data) {

System.out.println("Sorting using quick sort");

Arrays.sort(data); // 简化实现

}

}

// 冒泡排序策略

class BubbleSortStrategy implements SortStrategy {

@Override

public void sort(int\[\] data) {

System.out.println("Sorting using bubble sort");

// 简化实现:使用Java内置排序

Arrays.sort(data);

}

}

// 上下文类

class SortContext {

private SortStrategy strategy;

public SortContext(SortStrategy strategy) {

this.strategy = strategy;

}

public void setStrategy(SortStrategy strategy) {

this.strategy = strategy;

}

public void sort(int\[\] data) {

strategy.sort(data);

}

}

// 使用策略模式进行排序

public class StrategyPatternExample {

public static void main(String\[\] args) {

int\[\] data = {5, 3, 8, 6, 2};

SortContext context = new SortContext(new QuickSortStrategy());

context.sort(data);

System.out.println(Arrays.toString(data));

context.setStrategy(new BubbleSortStrategy());

context.sort(data);

System.out.println(Arrays.toString(data));

}

}

们可以使用策略模式来实现不同的排序算法。

总结

  • 工厂模式:通过工厂类来创建不同类型的对象,适用于需要动态决定创建哪种类型对象的场景。
  • 策略模式:通过上下文类和策略接口来选择不同的算法,适用于需要在运行时选择不同算法的场景。

这两种模式可以结合使用,例如,工厂模式可以用来创建策略对象。

相关推荐
Zane19943 天前
一个 new 就能创建对象,为什么还要拆出单例、工厂、建造者、原型四种模式?
设计模式
怕浪猫4 天前
一行命令复刻爆款视频,我把 Hypit 从安装跑到了出片
人工智能·设计模式·程序员
Zane19944 天前
函数式编程里的函数,其实不是你天天写的那个函数——三大编程范式的边界在哪
设计模式
Zane19945 天前
策略模式现在该不该上?一次讲清楚过度设计和设计不足怎么找平衡
设计模式
她说..5 天前
常见设计模式-模板方法模式
java·spring·设计模式·springboot
xiaofeiyang1506 天前
第六章 · 桥接 — 三支毛笔,画出九种颜色
设计模式
Shadow(⊙o⊙)6 天前
OTOL设计模式 One Thread One Loop
服务器·网络·设计模式
sarasuki7 天前
如何让LLM 能在半夜偷偷打开网易云呢?
人工智能·设计模式·agent
小王师傅667 天前
【设计模式】装饰模式(四):框架源码实战——从 Java I/O 到 Spring 到 MyBatis
java·设计模式
执明wa7 天前
Android RecyclerView 多类型, 多种 Item
android·xml·开发语言·设计模式·android studio