017-创建型设计模式
学习目标
通过本章学习,您将能够:
- 深入理解创建型设计模式的核心思想和应用场景
- 掌握单例模式的多种实现方式及其优缺点
- 理解工厂方法模式和抽象工厂模式的区别与联系
- 学会使用建造者模式构建复杂对象
- 掌握原型模式的实现和应用场景
- 能够在实际项目中合理选择和应用创建型模式
1. 创建型模式概述
1.1 基本概念
创建型设计模式关注对象的创建过程,它们提供了创建对象的机制,能够增加已有代码的灵活性和可复用性。这些模式将对象的创建逻辑封装起来,使得系统独立于如何创建、组合和表示对象。
核心思想:
- 封装对象创建的复杂性
- 使系统独立于对象的创建过程
- 提高代码的灵活性和可维护性
- 支持对象创建的多样化需求
主要优势:
- 灵活性:可以在运行时决定创建哪些对象
- 解耦性:客户端代码与具体类解耦
- 可扩展性:易于添加新的产品类型
- 一致性:提供统一的对象创建接口
/**
* 创建型模式的通用结构示例
*/
/**
* 产品接口 - 定义创建对象的公共接口
*/
public interface Product {
void operation();
String getProductInfo();
}
/**
* 具体产品实现
*/
public class ConcreteProductA implements Product {
@Override
public void operation() {
System.out.println("执行产品A的操作");
}
@Override
public String getProductInfo() {
return "产品A - 高性能版本";
}
}
public class ConcreteProductB implements Product {
@Override
public void operation() {
System.out.println("执行产品B的操作");
}
@Override
public String getProductInfo() {
return "产品B - 标准版本";
}
}
/**
* 创建者抽象类 - 定义创建产品的接口
*/
public abstract class Creator {
/**
* 工厂方法 - 由子类实现具体的创建逻辑
*/
public abstract Product createProduct();
/**
* 模板方法 - 定义使用产品的标准流程
*/
public void processProduct() {
Product product = createProduct();
System.out.println("创建产品: " + product.getProductInfo());
product.operation();
System.out.println("产品处理完成\n");
}
}
/**
* 具体创建者
*/
public class ConcreteCreatorA extends Creator {
@Override
public Product createProduct() {
return new ConcreteProductA();
}
}
public class ConcreteCreatorB extends Creator {
@Override
public Product createProduct() {
return new ConcreteProductB();
}
}
/**
* 客户端使用示例
*/
public class CreationalPatternDemo {
public static void main(String[] args) {
System.out.println("=== 创建型模式演示 ===");
// 使用不同的创建者创建不同的产品
Creator creatorA = new ConcreteCreatorA();
Creator creatorB = new ConcreteCreatorB();
System.out.println("使用创建者A:");
creatorA.processProduct();
System.out.println("使用创建者B:");
creatorB.processProduct();
}
}
1.2 创建型模式分类
按创建范围分类:
-
类创建型模式
- 使用继承关系来决定要创建的对象
- 将对象的创建延迟到子类
- 例如:工厂方法模式
-
对象创建型模式
- 将对象的创建委托给另一个对象
- 通过组合关系来创建对象
- 例如:抽象工厂模式、建造者模式
按创建复杂度分类:
-
简单创建
- 单例模式:控制实例数量
- 原型模式:通过克隆创建
-
复杂创建
- 工厂模式:封装创建逻辑
- 建造者模式:分步构建复杂对象
/**
* 创建型模式选择指南
*/
public class CreationalPatternSelector {
/**
* 根据需求选择合适的创建型模式
*/
public static String selectPattern(CreationRequirement requirement) {
switch (requirement.getScenario()) {
case SINGLE_INSTANCE:
return "单例模式 - 确保全局唯一实例";
case SIMPLE_OBJECT_CREATION:
if (requirement.hasMultipleVariants()) {
return "工厂方法模式 - 创建同一接口的不同实现";
} else {
return "简单工厂模式 - 封装对象创建逻辑";
}
case COMPLEX_OBJECT_CONSTRUCTION:
if (requirement.hasMultipleSteps()) {
return "建造者模式 - 分步构建复杂对象";
} else {
return "工厂方法模式 - 封装复杂创建逻辑";
}
case FAMILY_OF_OBJECTS:
return "抽象工厂模式 - 创建相关对象族";
case EXPENSIVE_OBJECT_CLONING:
return "原型模式 - 通过克隆避免重复创建";
case CONDITIONAL_CREATION:
if (requirement.hasComplexConditions()) {
return "抽象工厂模式 + 策略模式";
} else {
return "工厂方法模式";
}
default:
return "考虑使用简单的构造函数";
}
}
/**
* 创建需求枚举
*/
public enum CreationScenario {
SINGLE_INSTANCE, // 单实例需求
SIMPLE_OBJECT_CREATION, // 简单对象创建
COMPLEX_OBJECT_CONSTRUCTION, // 复杂对象构建
FAMILY_OF_OBJECTS, // 对象族创建
EXPENSIVE_OBJECT_CLONING, // 昂贵对象克隆
CONDITIONAL_CREATION // 条件性创建
}
/**
* 创建需求描述类
*/
public static class CreationRequirement {
private CreationScenario scenario;
private boolean multipleVariants;
private boolean multipleSteps;
private boolean complexConditions;
public CreationRequirement(CreationScenario scenario) {
this.scenario = scenario;
}
// Builder方法
public CreationRequirement withMultipleVariants() {
this.multipleVariants = true;
return this;
}
public CreationRequirement withMultipleSteps() {
this.multipleSteps = true;
return this;
}
public CreationRequirement withComplexConditions() {
this.complexConditions = true;
return this;
}
// Getters
public CreationScenario getScenario() { return scenario; }
public boolean hasMultipleVariants() { return multipleVariants; }
public boolean hasMultipleSteps() { return multipleSteps; }
public boolean hasComplexConditions() { return complexConditions; }
}
}
2. 单例模式(Singleton Pattern)
2.1 模式定义
单例模式确保一个类只有一个实例,并提供一个全局访问点。这个模式在需要控制实例数量、节约系统资源或需要全局状态管理时非常有用。
核心要素:
- 私有构造函数:防止外部直接创建实例
- 静态实例变量:保存唯一实例
- 静态获取方法:提供全局访问点
- 线程安全:确保多线程环境下的正确性
2.2 实现方式
2.2.1 饿汉式(Eager Initialization)
/**
* 饿汉式单例 - 类加载时就创建实例
* 优点:线程安全,实现简单
* 缺点:可能造成资源浪费
*/
public class EagerSingleton {
// 在类加载时就创建实例
private static final EagerSingleton INSTANCE = new EagerSingleton();
// 私有构造函数
private EagerSingleton() {
// 防止反射攻击
if (INSTANCE != null) {
throw new RuntimeException("单例对象不能重复创建");
}
System.out.println("EagerSingleton 实例被创建");
}
// 提供全局访问点
public static EagerSingleton getInstance() {
return INSTANCE;
}
// 业务方法
public void doSomething() {
System.out.println("执行饿汉式单例的业务逻辑");
}
// 防止序列化破坏单例
private Object readResolve() {
return INSTANCE;
}
}
2.2.2 懒汉式(Lazy Initialization)
/**
* 懒汉式单例 - 第一次使用时才创建实例
* 优点:延迟加载,节约资源
* 缺点:需要考虑线程安全
*/
public class LazySingleton {
private static LazySingleton instance;
private LazySingleton() {
System.out.println("LazySingleton 实例被创建");
}
/**
* 线程不安全的版本
*/
public static LazySingleton getInstanceUnsafe() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
/**
* 线程安全的版本 - 同步方法
* 缺点:性能较差,每次调用都需要同步
*/
public static synchronized LazySingleton getInstanceSafe() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
public void doSomething() {
System.out.println("执行懒汉式单例的业务逻辑");
}
}
2.2.3 双重检查锁定(Double-Checked Locking)
/**
* 双重检查锁定单例
* 优点:延迟加载 + 线程安全 + 高性能
* 注意:需要使用 volatile 关键字
*/
public class DoubleCheckedLockingSingleton {
// volatile 确保多线程环境下的可见性和有序性
private static volatile DoubleCheckedLockingSingleton instance;
private DoubleCheckedLockingSingleton() {
System.out.println("DoubleCheckedLockingSingleton 实例被创建");
}
public static DoubleCheckedLockingSingleton getInstance() {
// 第一次检查:避免不必要的同步
if (instance == null) {
synchronized (DoubleCheckedLockingSingleton.class) {
// 第二次检查:确保只创建一个实例
if (instance == null) {
instance = new DoubleCheckedLockingSingleton();
}
}
}
return instance;
}
public void doSomething() {
System.out.println("执行双重检查锁定单例的业务逻辑");
}
}
2.2.4 静态内部类(Static Inner Class)
/**
* 静态内部类单例
* 优点:延迟加载 + 线程安全 + 高性能 + 实现简单
* 推荐使用这种方式
*/
public class StaticInnerClassSingleton {
private StaticInnerClassSingleton() {
System.out.println("StaticInnerClassSingleton 实例被创建");
}
/**
* 静态内部类
* 只有在调用 getInstance() 时才会加载
*/
private static class SingletonHolder {
private static final StaticInnerClassSingleton INSTANCE = new StaticInnerClassSingleton();
}
public static StaticInnerClassSingleton getInstance() {
return SingletonHolder.INSTANCE;
}
public void doSomething() {
System.out.println("执行静态内部类单例的业务逻辑");
}
}
2.2.5 枚举单例(Enum Singleton)
/**
* 枚举单例
* 优点:实现简单、线程安全、防止反射和序列化攻击
* 《Effective Java》推荐的方式
*/
public enum EnumSingleton {
INSTANCE;
// 可以添加实例变量
private String data;
// 构造函数
EnumSingleton() {
System.out.println("EnumSingleton 实例被创建");
this.data = "初始数据";
}
// 业务方法
public void doSomething() {
System.out.println("执行枚举单例的业务逻辑: " + data);
}
// Getter和Setter
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
2.3 实际应用示例
2.3.1 配置管理器
/**
* 配置管理器单例
* 用于管理应用程序的全局配置
*/
public class ConfigurationManager {
private static volatile ConfigurationManager instance;
private Properties properties;
private String configFilePath;
private ConfigurationManager() {
this.properties = new Properties();
this.configFilePath = "application.properties";
loadConfiguration();
}
public static ConfigurationManager getInstance() {
if (instance == null) {
synchronized (ConfigurationManager.class) {
if (instance == null) {
instance = new ConfigurationManager();
}
}
}
return instance;
}
/**
* 加载配置文件
*/
private void loadConfiguration() {
try (InputStream input = getClass().getClassLoader().getResourceAsStream(configFilePath)) {
if (input != null) {
properties.load(input);
System.out.println("配置文件加载成功: " + configFilePath);
} else {
System.out.println("配置文件未找到,使用默认配置");
setDefaultConfiguration();
}
} catch (IOException e) {
System.err.println("配置文件加载失败: " + e.getMessage());
setDefaultConfiguration();
}
}
/**
* 设置默认配置
*/
private void setDefaultConfiguration() {
properties.setProperty("database.url", "jdbc:mysql://localhost:3306/mydb");
properties.setProperty("database.username", "root");
properties.setProperty("database.password", "password");
properties.setProperty("app.name", "MyApplication");
properties.setProperty("app.version", "1.0.0");
}
/**
* 获取配置值
*/
public String getProperty(String key) {
return properties.getProperty(key);
}
/**
* 获取配置值(带默认值)
*/
public String getProperty(String key, String defaultValue) {
return properties.getProperty(key, defaultValue);
}
/**
* 设置配置值
*/
public void setProperty(String key, String value) {
properties.setProperty(key, value);
}
/**
* 获取所有配置
*/
public Properties getAllProperties() {
return new Properties(properties); // 返回副本,防止外部修改
}
/**
* 重新加载配置
*/
public synchronized void reloadConfiguration() {
properties.clear();
loadConfiguration();
System.out.println("配置已重新加载");
}
/**
* 保存配置到文件
*/
public synchronized void saveConfiguration() {
try (OutputStream output = new FileOutputStream(configFilePath)) {
properties.store(output, "Application Configuration");
System.out.println("配置已保存到文件: " + configFilePath);
} catch (IOException e) {
System.err.println("配置保存失败: " + e.getMessage());
}
}
}
2.3.2 日志管理器
/**
* 日志管理器单例
* 提供全局统一的日志记录功能
*/
public class LogManager {
private static final LogManager INSTANCE = new LogManager();
private PrintWriter logWriter;
private String logFilePath;
private LogLevel currentLogLevel;
// 日志级别枚举
public enum LogLevel {
DEBUG(0), INFO(1), WARN(2), ERROR(3);
private final int level;
LogLevel(int level) {
this.level = level;
}
public int getLevel() {
return level;
}
}
private LogManager() {
this.logFilePath = "application.log";
this.currentLogLevel = LogLevel.INFO;
initializeLogWriter();
}
public static LogManager getInstance() {
return INSTANCE;
}
/**
* 初始化日志写入器
*/
private void initializeLogWriter() {
try {
logWriter = new PrintWriter(new FileWriter(logFilePath, true));
System.out.println("日志管理器初始化成功,日志文件: " + logFilePath);
} catch (IOException e) {
System.err.println("日志文件创建失败: " + e.getMessage());
// 如果文件创建失败,使用控制台输出
logWriter = new PrintWriter(System.out);
}
}
/**
* 记录日志
*/
private synchronized void log(LogLevel level, String message, Throwable throwable) {
if (level.getLevel() >= currentLogLevel.getLevel()) {
String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
String logEntry = String.format("[%s] %s - %s", timestamp, level.name(), message);
logWriter.println(logEntry);
if (throwable != null) {
throwable.printStackTrace(logWriter);
}
logWriter.flush();
// 同时输出到控制台(可选)
System.out.println(logEntry);
if (throwable != null) {
throwable.printStackTrace();
}
}
}
/**
* DEBUG级别日志
*/
public void debug(String message) {
log(LogLevel.DEBUG, message, null);
}
/**
* INFO级别日志
*/
public void info(String message) {
log(LogLevel.INFO, message, null);
}
/**
* WARN级别日志
*/
public void warn(String message) {
log(LogLevel.WARN, message, null);
}
/**
* ERROR级别日志
*/
public void error(String message) {
log(LogLevel.ERROR, message, null);
}
/**
* ERROR级别日志(带异常)
*/
public void error(String message, Throwable throwable) {
log(LogLevel.ERROR, message, throwable);
}
/**
* 设置日志级别
*/
public void setLogLevel(LogLevel level) {
this.currentLogLevel = level;
info("日志级别已设置为: " + level.name());
}
/**
* 关闭日志管理器
*/
public synchronized void close() {
if (logWriter != null) {
logWriter.close();
System.out.println("日志管理器已关闭");
}
}
/**
* JVM关闭时自动关闭日志管理器
*/
static {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
LogManager.getInstance().close();
}));
}
}
2.4 单例模式的优缺点
优点:
- 控制实例数量,节约系统资源
- 提供全局访问点,便于管理
- 延迟初始化,提高启动性能
- 避免对共享资源的多重占用
缺点:
- 违反单一职责原则
- 难以进行单元测试
- 可能成为系统的瓶颈
- 在多线程环境下需要特别注意
使用场景:
- 配置管理器
- 日志管理器
- 数据库连接池
- 缓存管理器
- 线程池管理器
/**
* 单例模式使用示例
*/
public class SingletonDemo {
public static void main(String[] args) {
System.out.println("=== 单例模式演示 ===");
// 配置管理器使用
ConfigurationManager config = ConfigurationManager.getInstance();
System.out.println("数据库URL: " + config.getProperty("database.url"));
System.out.println("应用名称: " + config.getProperty("app.name"));
// 日志管理器使用
LogManager logger = LogManager.getInstance();
logger.info("应用程序启动");
logger.warn("这是一个警告消息");
logger.error("这是一个错误消息");
// 验证单例特性
ConfigurationManager config2 = ConfigurationManager.getInstance();
System.out.println("两个实例是否相同: " + (config == config2));
// 枚举单例使用
EnumSingleton enumSingleton = EnumSingleton.INSTANCE;
enumSingleton.setData("更新后的数据");
enumSingleton.doSomething();
}
}
3. 工厂方法模式(Factory Method Pattern)
3.1 模式定义
工厂方法模式定义了一个创建对象的接口,但让子类决定实例化哪一个类。工厂方法让类的实例化推迟到子类。
核心思想:
- 将对象的创建延迟到子类
- 通过继承来决定创建哪种产品
- 遵循开闭原则,易于扩展
UML类图:
3.2 基本实现
/**
* 工厂方法模式基本实现
*/
/**
* 产品接口
*/
public interface Document {
void open();
void save();
void close();
String getType();
}
/**
* 具体产品:Word文档
*/
public class WordDocument implements Document {
private String fileName;
public WordDocument(String fileName) {
this.fileName = fileName;
}
@Override
public void open() {
System.out.println("打开Word文档: " + fileName);
}
@Override
public void save() {
System.out.println("保存Word文档: " + fileName);
}
@Override
public void close() {
System.out.println("关闭Word文档: " + fileName);
}
@Override
public String getType() {
return "Word Document";
}
}
/**
* 具体产品:PDF文档
*/
public class PdfDocument implements Document {
private String fileName;
public PdfDocument(String fileName) {
this.fileName = fileName;
}
@Override
public void open() {
System.out.println("打开PDF文档: " + fileName);
}
@Override
public void save() {
System.out.println("保存PDF文档: " + fileName);
}
@Override
public void close() {
System.out.println("关闭PDF文档: " + fileName);
}
@Override
public String getType() {
return "PDF Document";
}
}
/**
* 抽象创建者
*/
public abstract class DocumentCreator {
/**
* 工厂方法 - 由子类实现
*/
public abstract Document createDocument(String fileName);
/**
* 模板方法 - 定义文档处理的标准流程
*/
public void processDocument(String fileName) {
System.out.println("\n=== 开始处理文档 ===");
// 使用工厂方法创建文档
Document document = createDocument(fileName);
// 标准的文档处理流程
document.open();
// 执行特定的处理逻辑
performSpecificProcessing(document);
document.save();
document.close();
System.out.println("=== 文档处理完成 ===\n");
}
/**
* 钩子方法 - 子类可以重写以提供特定的处理逻辑
*/
protected void performSpecificProcessing(Document document) {
System.out.println("执行通用文档处理逻辑");
}
}
/**
* 具体创建者:Word文档创建者
*/
public class WordDocumentCreator extends DocumentCreator {
@Override
public Document createDocument(String fileName) {
System.out.println("创建Word文档实例");
return new WordDocument(fileName);
}
@Override
protected void performSpecificProcessing(Document document) {
System.out.println("执行Word文档特有的处理逻辑:");
System.out.println("- 检查拼写和语法");
System.out.println("- 应用样式和格式");
System.out.println("- 生成目录");
}
}
/**
* 具体创建者:PDF文档创建者
*/
public class PdfDocumentCreator extends DocumentCreator {
@Override
public Document createDocument(String fileName) {
System.out.println("创建PDF文档实例");
return new PdfDocument(fileName);
}
@Override
protected void performSpecificProcessing(Document document) {
System.out.println("执行PDF文档特有的处理逻辑:");
System.out.println("- 优化文档大小");
System.out.println("- 设置安全权限");
System.out.println("- 添加数字签名");
}
}
3.3 实际应用示例
3.3.1 数据库连接工厂
/**
* 数据库连接工厂示例
*/
/**
* 数据库连接接口
*/
public interface DatabaseConnection {
void connect();
void disconnect();
void executeQuery(String sql);
String getConnectionInfo();
}
/**
* MySQL连接实现
*/
public class MySQLConnection implements DatabaseConnection {
private String host;
private int port;
private String database;
private boolean connected;
public MySQLConnection(String host, int port, String database) {
this.host = host;
this.port = port;
this.database = database;
this.connected = false;
}
@Override
public void connect() {
System.out.println("连接到MySQL数据库: " + getConnectionInfo());
// 模拟连接逻辑
try {
Thread.sleep(100); // 模拟连接延迟
connected = true;
System.out.println("MySQL连接成功");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
@Override
public void disconnect() {
if (connected) {
System.out.println("断开MySQL连接");
connected = false;
}
}
@Override
public void executeQuery(String sql) {
if (connected) {
System.out.println("在MySQL中执行查询: " + sql);
} else {
System.out.println("错误:MySQL连接未建立");
}
}
@Override
public String getConnectionInfo() {
return String.format("mysql://%s:%d/%s", host, port, database);
}
}
/**
* PostgreSQL连接实现
*/
public class PostgreSQLConnection implements DatabaseConnection {
private String host;
private int port;
private String database;
private boolean connected;
public PostgreSQLConnection(String host, int port, String database) {
this.host = host;
this.port = port;
this.database = database;
this.connected = false;
}
@Override
public void connect() {
System.out.println("连接到PostgreSQL数据库: " + getConnectionInfo());
try {
Thread.sleep(150); // 模拟连接延迟
connected = true;
System.out.println("PostgreSQL连接成功");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
@Override
public void disconnect() {
if (connected) {
System.out.println("断开PostgreSQL连接");
connected = false;
}
}
@Override
public void executeQuery(String sql) {
if (connected) {
System.out.println("在PostgreSQL中执行查询: " + sql);
} else {
System.out.println("错误:PostgreSQL连接未建立");
}
}
@Override
public String getConnectionInfo() {
return String.format("postgresql://%s:%d/%s", host, port, database);
}
}
/**
* 抽象数据库工厂
*/
public abstract class DatabaseConnectionFactory {
/**
* 工厂方法 - 创建数据库连接
*/
public abstract DatabaseConnection createConnection(String host, int port, String database);
/**
* 模板方法 - 标准的数据库操作流程
*/
public void performDatabaseOperation(String host, int port, String database, String sql) {
System.out.println("\n=== 开始数据库操作 ===");
DatabaseConnection connection = createConnection(host, port, database);
try {
connection.connect();
// 执行预处理操作
performPreProcessing(connection);
// 执行主要查询
connection.executeQuery(sql);
// 执行后处理操作
performPostProcessing(connection);
} finally {
connection.disconnect();
}
System.out.println("=== 数据库操作完成 ===\n");
}
/**
* 钩子方法 - 预处理
*/
protected void performPreProcessing(DatabaseConnection connection) {
System.out.println("执行通用预处理操作");
}
/**
* 钩子方法 - 后处理
*/
protected void performPostProcessing(DatabaseConnection connection) {
System.out.println("执行通用后处理操作");
}
}
/**
* MySQL连接工厂
*/
public class MySQLConnectionFactory extends DatabaseConnectionFactory {
@Override
public DatabaseConnection createConnection(String host, int port, String database) {
System.out.println("创建MySQL连接实例");
return new MySQLConnection(host, port, database);
}
@Override
protected void performPreProcessing(DatabaseConnection connection) {
super.performPreProcessing(connection);
System.out.println("MySQL特有预处理:设置字符集为UTF-8");
}
@Override
protected void performPostProcessing(DatabaseConnection connection) {
super.performPostProcessing(connection);
System.out.println("MySQL特有后处理:清理查询缓存");
}
}
/**
* PostgreSQL连接工厂
*/
public class PostgreSQLConnectionFactory extends DatabaseConnectionFactory {
@Override
public DatabaseConnection createConnection(String host, int port, String database) {
System.out.println("创建PostgreSQL连接实例");
return new PostgreSQLConnection(host, port, database);
}
@Override
protected void performPreProcessing(DatabaseConnection connection) {
super.performPreProcessing(connection);
System.out.println("PostgreSQL特有预处理:设置事务隔离级别");
}
@Override
protected void performPostProcessing(DatabaseConnection connection) {
super.performPostProcessing(connection);
System.out.println("PostgreSQL特有后处理:分析查询性能");
}
}
3.3.2 消息处理器工厂
/**
* 消息处理器工厂示例
*/
/**
* 消息接口
*/
public interface Message {
String getContent();
String getType();
long getTimestamp();
}
/**
* 消息处理器接口
*/
public interface MessageProcessor {
void processMessage(Message message);
boolean canHandle(String messageType);
String getProcessorType();
}
/**
* 邮件消息实现
*/
public class EmailMessage implements Message {
private String content;
private long timestamp;
public EmailMessage(String content) {
this.content = content;
this.timestamp = System.currentTimeMillis();
}
@Override
public String getContent() {
return content;
}
@Override
public String getType() {
return "EMAIL";
}
@Override
public long getTimestamp() {
return timestamp;
}
}
/**
* 短信消息实现
*/
public class SmsMessage implements Message {
private String content;
private long timestamp;
public SmsMessage(String content) {
this.content = content;
this.timestamp = System.currentTimeMillis();
}
@Override
public String getContent() {
return content;
}
@Override
public String getType() {
return "SMS";
}
@Override
public long getTimestamp() {
return timestamp;
}
}
/**
* 邮件处理器
*/
public class EmailProcessor implements MessageProcessor {
@Override
public void processMessage(Message message) {
System.out.println("处理邮件消息:");
System.out.println("- 验证邮件格式");
System.out.println("- 检查垃圾邮件");
System.out.println("- 发送邮件: " + message.getContent());
System.out.println("- 记录发送日志");
}
@Override
public boolean canHandle(String messageType) {
return "EMAIL".equals(messageType);
}
@Override
public String getProcessorType() {
return "Email Processor";
}
}
/**
* 短信处理器
*/
public class SmsProcessor implements MessageProcessor {
@Override
public void processMessage(Message message) {
System.out.println("处理短信消息:");
System.out.println("- 检查短信长度");
System.out.println("- 验证手机号码");
System.out.println("- 发送短信: " + message.getContent());
System.out.println("- 更新发送统计");
}
@Override
public boolean canHandle(String messageType) {
return "SMS".equals(messageType);
}
@Override
public String getProcessorType() {
return "SMS Processor";
}
}
/**
* 抽象消息处理工厂
*/
public abstract class MessageProcessorFactory {
/**
* 工厂方法 - 创建消息处理器
*/
public abstract MessageProcessor createProcessor();
/**
* 工厂方法 - 创建消息
*/
public abstract Message createMessage(String content);
/**
* 模板方法 - 完整的消息处理流程
*/
public void handleMessage(String content) {
System.out.println("\n=== 开始消息处理 ===");
// 创建消息和处理器
Message message = createMessage(content);
MessageProcessor processor = createProcessor();
// 验证处理器是否能处理该消息
if (processor.canHandle(message.getType())) {
System.out.println("使用处理器: " + processor.getProcessorType());
// 执行预处理
performPreProcessing(message);
// 处理消息
processor.processMessage(message);
// 执行后处理
performPostProcessing(message);
} else {
System.out.println("错误:处理器无法处理该类型的消息");
}
System.out.println("=== 消息处理完成 ===\n");
}
/**
* 钩子方法 - 预处理
*/
protected void performPreProcessing(Message message) {
System.out.println("执行通用预处理:记录消息接收时间");
}
/**
* 钩子方法 - 后处理
*/
protected void performPostProcessing(Message message) {
System.out.println("执行通用后处理:更新处理统计");
}
}
/**
* 邮件处理工厂
*/
public class EmailProcessorFactory extends MessageProcessorFactory {
@Override
public MessageProcessor createProcessor() {
System.out.println("创建邮件处理器实例");
return new EmailProcessor();
}
@Override
public Message createMessage(String content) {
System.out.println("创建邮件消息实例");
return new EmailMessage(content);
}
@Override
protected void performPreProcessing(Message message) {
super.performPreProcessing(message);
System.out.println("邮件特有预处理:验证邮件头信息");
}
}
/**
* 短信处理工厂
*/
public class SmsProcessorFactory extends MessageProcessorFactory {
@Override
public MessageProcessor createProcessor() {
System.out.println("创建短信处理器实例");
return new SmsProcessor();
}
@Override
public Message createMessage(String content) {
System.out.println("创建短信消息实例");
return new SmsMessage(content);
}
@Override
protected void performPreProcessing(Message message) {
super.performPreProcessing(message);
System.out.println("短信特有预处理:检查发送频率限制");
}
}
3.4 工厂方法模式的优缺点
优点:
- 遵循开闭原则,易于扩展
- 避免创建者和具体产品的紧耦合
- 符合单一职责原则
- 提供了一种委托的方式来创建对象
缺点:
- 增加了系统的复杂性
- 需要创建更多的类
- 客户端需要知道具体的工厂类
使用场景:
- 创建对象需要大量重复代码
- 客户端不依赖于产品类实例如何被创建
- 一个类通过其子类来指定创建哪个对象
/**
* 工厂方法模式使用示例
*/
public class FactoryMethodDemo {
public static void main(String[] args) {
System.out.println("=== 工厂方法模式演示 ===");
// 文档处理示例
DocumentCreator wordCreator = new WordDocumentCreator();
DocumentCreator pdfCreator = new PdfDocumentCreator();
wordCreator.processDocument("报告.docx");
pdfCreator.processDocument("手册.pdf");
// 数据库连接示例
DatabaseConnectionFactory mysqlFactory = new MySQLConnectionFactory();
DatabaseConnectionFactory postgresFactory = new PostgreSQLConnectionFactory();
mysqlFactory.performDatabaseOperation("localhost", 3306, "testdb", "SELECT * FROM users");
postgresFactory.performDatabaseOperation("localhost", 5432, "testdb", "SELECT * FROM products");
// 消息处理示例
MessageProcessorFactory emailFactory = new EmailProcessorFactory();
MessageProcessorFactory smsFactory = new SmsProcessorFactory();
emailFactory.handleMessage("欢迎使用我们的服务!");
smsFactory.handleMessage("您的验证码是:123456");
}
}
4. 抽象工厂模式(Abstract Factory Pattern)
4.1 模式定义
抽象工厂模式提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。它是工厂方法模式的进一步抽象,用于创建产品族。
核心思想:
- 产品族概念:一组相关的产品对象
- 多个工厂方法:每个工厂负责创建一个产品族
- 客户端解耦:客户端不依赖具体产品类
- 一致性保证:确保产品族的一致性
4.2 基本实现
以GUI组件库为例,展示抽象工厂模式的实现:
/**
* 抽象工厂模式实现 - GUI组件库
*/
/**
* 抽象产品A - 按钮
*/
public interface Button {
void render();
void onClick();
String getStyle();
}
/**
* 抽象产品B - 文本框
*/
public interface TextField {
void render();
void setText(String text);
String getText();
String getStyle();
}
/**
* 抽象产品C - 复选框
*/
public interface CheckBox {
void render();
void setChecked(boolean checked);
boolean isChecked();
String getStyle();
}
/**
* Windows风格按钮
*/
public class WindowsButton implements Button {
@Override
public void render() {
System.out.println("渲染Windows风格按钮 - 方形边框,蓝色背景");
}
@Override
public void onClick() {
System.out.println("Windows按钮点击 - 播放系统点击音效");
}
@Override
public String getStyle() {
return "Windows Style";
}
}
/**
* Windows风格文本框
*/
public class WindowsTextField implements TextField {
private String text = "";
@Override
public void render() {
System.out.println("渲染Windows风格文本框 - 白色背景,黑色边框");
}
@Override
public void setText(String text) {
this.text = text;
System.out.println("Windows文本框设置文本: " + text);
}
@Override
public String getText() {
return text;
}
@Override
public String getStyle() {
return "Windows Style";
}
}
/**
* Windows风格复选框
*/
public class WindowsCheckBox implements CheckBox {
private boolean checked = false;
@Override
public void render() {
System.out.println("渲染Windows风格复选框 - 方形," + (checked ? "已选中" : "未选中"));
}
@Override
public void setChecked(boolean checked) {
this.checked = checked;
System.out.println("Windows复选框状态: " + (checked ? "选中" : "取消选中"));
}
@Override
public boolean isChecked() {
return checked;
}
@Override
public String getStyle() {
return "Windows Style";
}
}
/**
* Mac风格按钮
*/
public class MacButton implements Button {
@Override
public void render() {
System.out.println("渲染Mac风格按钮 - 圆角边框,渐变背景");
}
@Override
public void onClick() {
System.out.println("Mac按钮点击 - 优雅的动画效果");
}
@Override
public String getStyle() {
return "Mac Style";
}
}
/**
* Mac风格文本框
*/
public class MacTextField implements TextField {
private String text = "";
@Override
public void render() {
System.out.println("渲染Mac风格文本框 - 圆角边框,阴影效果");
}
@Override
public void setText(String text) {
this.text = text;
System.out.println("Mac文本框设置文本: " + text);
}
@Override
public String getText() {
return text;
}
@Override
public String getStyle() {
return "Mac Style";
}
}
/**
* Mac风格复选框
*/
public class MacCheckBox implements CheckBox {
private boolean checked = false;
@Override
public void render() {
System.out.println("渲染Mac风格复选框 - 圆形," + (checked ? "蓝色填充" : "空心"));
}
@Override
public void setChecked(boolean checked) {
this.checked = checked;
System.out.println("Mac复选框状态: " + (checked ? "选中" : "取消选中"));
}
@Override
public boolean isChecked() {
return checked;
}
@Override
public String getStyle() {
return "Mac Style";
}
}
/**
* 抽象工厂
*/
public abstract class GUIFactory {
public abstract Button createButton();
public abstract TextField createTextField();
public abstract CheckBox createCheckBox();
/**
* 工厂选择方法
*/
public static GUIFactory getFactory(String osType) {
switch (osType.toLowerCase()) {
case "windows":
return new WindowsFactory();
case "mac":
return new MacFactory();
case "linux":
return new LinuxFactory();
default:
throw new IllegalArgumentException("不支持的操作系统: " + osType);
}
}
/**
* 创建完整的UI组件集合
*/
public UIComponentSet createUIComponentSet() {
return new UIComponentSet(
createButton(),
createTextField(),
createCheckBox()
);
}
}
/**
* Windows工厂
*/
public class WindowsFactory extends GUIFactory {
@Override
public Button createButton() {
System.out.println("创建Windows按钮实例");
return new WindowsButton();
}
@Override
public TextField createTextField() {
System.out.println("创建Windows文本框实例");
return new WindowsTextField();
}
@Override
public CheckBox createCheckBox() {
System.out.println("创建Windows复选框实例");
return new WindowsCheckBox();
}
}
/**
* Mac工厂
*/
public class MacFactory extends GUIFactory {
@Override
public Button createButton() {
System.out.println("创建Mac按钮实例");
return new MacButton();
}
@Override
public TextField createTextField() {
System.out.println("创建Mac文本框实例");
return new MacTextField();
}
@Override
public CheckBox createCheckBox() {
System.out.println("创建Mac复选框实例");
return new MacCheckBox();
}
}
/**
* Linux工厂(扩展示例)
*/
public class LinuxFactory extends GUIFactory {
@Override
public Button createButton() {
System.out.println("创建Linux按钮实例");
return new LinuxButton();
}
@Override
public TextField createTextField() {
System.out.println("创建Linux文本框实例");
return new LinuxTextField();
}
@Override
public CheckBox createCheckBox() {
System.out.println("创建Linux复选框实例");
return new LinuxCheckBox();
}
}
/**
* UI组件集合
*/
public class UIComponentSet {
private Button button;
private TextField textField;
private CheckBox checkBox;
public UIComponentSet(Button button, TextField textField, CheckBox checkBox) {
this.button = button;
this.textField = textField;
this.checkBox = checkBox;
}
public void renderAll() {
System.out.println("\n=== 渲染UI组件集合 ===");
button.render();
textField.render();
checkBox.render();
System.out.println("UI风格: " + button.getStyle());
}
public void interactAll() {
System.out.println("\n=== UI交互演示 ===");
textField.setText("Hello World");
checkBox.setChecked(true);
button.onClick();
}
// Getters
public Button getButton() { return button; }
public TextField getTextField() { return textField; }
public CheckBox getCheckBox() { return checkBox; }
}
/**
* 客户端应用
*/
public class Application {
private UIComponentSet uiComponents;
private String osType;
public Application(String osType) {
this.osType = osType;
initializeUI();
}
private void initializeUI() {
System.out.println("\n=== 初始化应用程序 (" + osType + ") ===");
GUIFactory factory = GUIFactory.getFactory(osType);
uiComponents = factory.createUIComponentSet();
}
public void run() {
System.out.println("\n=== 应用程序运行 ===");
uiComponents.renderAll();
uiComponents.interactAll();
}
public void switchTheme(String newOsType) {
System.out.println("\n=== 切换主题到: " + newOsType + " ===");
this.osType = newOsType;
initializeUI();
run();
}
}
4.3 实际应用示例
4.3.1 数据库访问工厂
/**
* 数据库访问抽象工厂示例
*/
/**
* 数据库连接接口
*/
public interface DatabaseConnection {
void connect();
void disconnect();
boolean isConnected();
String getConnectionString();
}
/**
* 数据库命令接口
*/
public interface DatabaseCommand {
void execute(String sql);
ResultSet executeQuery(String sql);
void setConnection(DatabaseConnection connection);
}
/**
* 数据库事务接口
*/
public interface DatabaseTransaction {
void begin();
void commit();
void rollback();
boolean isActive();
}
/**
* MySQL实现族
*/
public class MySQLConnection implements DatabaseConnection {
private boolean connected = false;
private String host, database;
private int port;
public MySQLConnection(String host, int port, String database) {
this.host = host;
this.port = port;
this.database = database;
}
@Override
public void connect() {
System.out.println("连接到MySQL数据库: " + getConnectionString());
connected = true;
}
@Override
public void disconnect() {
System.out.println("断开MySQL数据库连接");
connected = false;
}
@Override
public boolean isConnected() {
return connected;
}
@Override
public String getConnectionString() {
return String.format("mysql://%s:%d/%s", host, port, database);
}
}
public class MySQLCommand implements DatabaseCommand {
private DatabaseConnection connection;
@Override
public void execute(String sql) {
System.out.println("执行MySQL命令: " + sql);
System.out.println("使用MySQL特有的执行引擎");
}
@Override
public ResultSet executeQuery(String sql) {
System.out.println("执行MySQL查询: " + sql);
System.out.println("返回MySQL ResultSet");
return null; // 简化示例
}
@Override
public void setConnection(DatabaseConnection connection) {
this.connection = connection;
}
}
public class MySQLTransaction implements DatabaseTransaction {
private boolean active = false;
@Override
public void begin() {
System.out.println("开始MySQL事务");
active = true;
}
@Override
public void commit() {
if (active) {
System.out.println("提交MySQL事务");
active = false;
}
}
@Override
public void rollback() {
if (active) {
System.out.println("回滚MySQL事务");
active = false;
}
}
@Override
public boolean isActive() {
return active;
}
}
/**
* PostgreSQL实现族
*/
public class PostgreSQLConnection implements DatabaseConnection {
private boolean connected = false;
private String host, database;
private int port;
public PostgreSQLConnection(String host, int port, String database) {
this.host = host;
this.port = port;
this.database = database;
}
@Override
public void connect() {
System.out.println("连接到PostgreSQL数据库: " + getConnectionString());
connected = true;
}
@Override
public void disconnect() {
System.out.println("断开PostgreSQL数据库连接");
connected = false;
}
@Override
public boolean isConnected() {
return connected;
}
@Override
public String getConnectionString() {
return String.format("postgresql://%s:%d/%s", host, port, database);
}
}
public class PostgreSQLCommand implements DatabaseCommand {
private DatabaseConnection connection;
@Override
public void execute(String sql) {
System.out.println("执行PostgreSQL命令: " + sql);
System.out.println("使用PostgreSQL特有的执行引擎");
}
@Override
public ResultSet executeQuery(String sql) {
System.out.println("执行PostgreSQL查询: " + sql);
System.out.println("返回PostgreSQL ResultSet");
return null; // 简化示例
}
@Override
public void setConnection(DatabaseConnection connection) {
this.connection = connection;
}
}
public class PostgreSQLTransaction implements DatabaseTransaction {
private boolean active = false;
@Override
public void begin() {
System.out.println("开始PostgreSQL事务");
active = true;
}
@Override
public void commit() {
if (active) {
System.out.println("提交PostgreSQL事务");
active = false;
}
}
@Override
public void rollback() {
if (active) {
System.out.println("回滚PostgreSQL事务");
active = false;
}
}
@Override
public boolean isActive() {
return active;
}
}
/**
* 数据库抽象工厂
*/
public abstract class DatabaseFactory {
public abstract DatabaseConnection createConnection(String host, int port, String database);
public abstract DatabaseCommand createCommand();
public abstract DatabaseTransaction createTransaction();
// 工厂注册表
private static final Map<String, Supplier<DatabaseFactory>> factories = new HashMap<>();
static {
factories.put("mysql", MySQLFactory::new);
factories.put("postgresql", PostgreSQLFactory::new);
factories.put("oracle", OracleFactory::new);
}
public static DatabaseFactory getFactory(String dbType) {
Supplier<DatabaseFactory> factorySupplier = factories.get(dbType.toLowerCase());
if (factorySupplier == null) {
throw new IllegalArgumentException("不支持的数据库类型: " + dbType);
}
return factorySupplier.get();
}
/**
* 创建完整的数据库访问套件
*/
public DatabaseAccessSuite createDatabaseSuite(String host, int port, String database) {
DatabaseConnection connection = createConnection(host, port, database);
DatabaseCommand command = createCommand();
DatabaseTransaction transaction = createTransaction();
command.setConnection(connection);
return new DatabaseAccessSuite(connection, command, transaction);
}
}
/**
* MySQL工厂
*/
public class MySQLFactory extends DatabaseFactory {
@Override
public DatabaseConnection createConnection(String host, int port, String database) {
return new MySQLConnection(host, port, database);
}
@Override
public DatabaseCommand createCommand() {
return new MySQLCommand();
}
@Override
public DatabaseTransaction createTransaction() {
return new MySQLTransaction();
}
}
/**
* PostgreSQL工厂
*/
public class PostgreSQLFactory extends DatabaseFactory {
@Override
public DatabaseConnection createConnection(String host, int port, String database) {
return new PostgreSQLConnection(host, port, database);
}
@Override
public DatabaseCommand createCommand() {
return new PostgreSQLCommand();
}
@Override
public DatabaseTransaction createTransaction() {
return new PostgreSQLTransaction();
}
}
/**
* 数据库访问套件
*/
public class DatabaseAccessSuite {
private DatabaseConnection connection;
private DatabaseCommand command;
private DatabaseTransaction transaction;
public DatabaseAccessSuite(DatabaseConnection connection,
DatabaseCommand command,
DatabaseTransaction transaction) {
this.connection = connection;
this.command = command;
this.transaction = transaction;
}
public void executeInTransaction(String... sqls) {
try {
connection.connect();
transaction.begin();
for (String sql : sqls) {
command.execute(sql);
}
transaction.commit();
System.out.println("事务执行成功");
} catch (Exception e) {
transaction.rollback();
System.out.println("事务执行失败,已回滚");
} finally {
connection.disconnect();
}
}
// Getters
public DatabaseConnection getConnection() { return connection; }
public DatabaseCommand getCommand() { return command; }
public DatabaseTransaction getTransaction() { return transaction; }
}
4.4 抽象工厂模式的优缺点
优点:
- 产品族一致性:确保相关产品的兼容性
- 易于切换产品族:通过更换工厂实现整体切换
- 符合开闭原则:新增产品族不影响现有代码
- 客户端解耦:客户端不依赖具体产品实现
- 封装性好:将产品族的创建逻辑集中管理
缺点:
- 扩展困难:新增产品类型需要修改所有工厂
- 复杂性增加:类的数量成倍增长
- 抽象层次高:理解和维护成本较高
- 违反开闭原则:添加新产品需要修改抽象工厂接口
使用场景:
- 跨平台应用:需要支持多个操作系统的GUI应用
- 多数据库支持:需要支持多种数据库的应用系统
- 主题切换:需要支持多种UI主题的应用
- 产品线管理:管理多个相关产品系列的系统
- 系统移植:需要在不同环境间移植的系统
/**
* 抽象工厂模式使用示例
*/
public class AbstractFactoryDemo {
public static void main(String[] args) {
System.out.println("=== 抽象工厂模式演示 ===");
// GUI应用示例
demonstrateGUIApplication();
// 数据库访问示例
demonstrateDatabaseAccess();
}
private static void demonstrateGUIApplication() {
System.out.println("\n=== GUI应用演示 ===");
// 创建Windows应用
Application windowsApp = new Application("windows");
windowsApp.run();
// 切换到Mac主题
windowsApp.switchTheme("mac");
// 创建Linux应用
Application linuxApp = new Application("linux");
linuxApp.run();
}
private static void demonstrateDatabaseAccess() {
System.out.println("\n=== 数据库访问演示 ===");
// MySQL数据库操作
DatabaseFactory mysqlFactory = DatabaseFactory.getFactory("mysql");
DatabaseAccessSuite mysqlSuite = mysqlFactory.createDatabaseSuite(
"localhost", 3306, "testdb");
mysqlSuite.executeInTransaction(
"INSERT INTO users (name) VALUES ('张三')",
"UPDATE users SET age = 25 WHERE name = '张三'"
);
// PostgreSQL数据库操作
DatabaseFactory postgresFactory = DatabaseFactory.getFactory("postgresql");
DatabaseAccessSuite postgresSuite = postgresFactory.createDatabaseSuite(
"localhost", 5432, "testdb");
postgresSuite.executeInTransaction(
"INSERT INTO products (name) VALUES ('产品A')",
"UPDATE products SET price = 99.99 WHERE name = '产品A'"
);
}
}
5. 建造者模式(Builder Pattern)
5.1 模式定义
建造者模式将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。它通过一步一步地构建复杂对象,允许用户只通过指定复杂对象的类型和内容就可以构建它们。
核心思想:
- 分步构建:将复杂对象的创建过程分解为多个简单步骤
- 链式调用:提供流畅的API接口
- 参数验证:在构建过程中进行参数校验
- 不可变对象:构建完成后对象状态不可改变
5.2 基本实现
以计算机配置为例,展示建造者模式的实现:
/**
* 建造者模式实现 - 计算机配置
*/
/**
* 产品类 - 计算机
*/
public class Computer {
// 必需参数
private final String cpu;
private final String memory;
// 可选参数
private final String storage;
private final String graphicsCard;
private final String motherboard;
private final String powerSupply;
private final String computerCase;
private final boolean hasWifi;
private final boolean hasBluetooth;
// 私有构造函数,只能通过Builder创建
private Computer(Builder builder) {
this.cpu = builder.cpu;
this.memory = builder.memory;
this.storage = builder.storage;
this.graphicsCard = builder.graphicsCard;
this.motherboard = builder.motherboard;
this.powerSupply = builder.powerSupply;
this.computerCase = builder.computerCase;
this.hasWifi = builder.hasWifi;
this.hasBluetooth = builder.hasBluetooth;
}
/**
* 静态内部建造者类
*/
public static class Builder {
// 必需参数
private final String cpu;
private final String memory;
// 可选参数 - 初始化为默认值
private String storage = "500GB SSD";
private String graphicsCard = "集成显卡";
private String motherboard = "标准主板";
private String powerSupply = "500W";
private String computerCase = "标准机箱";
private boolean hasWifi = false;
private boolean hasBluetooth = false;
/**
* 构造函数 - 必需参数
*/
public Builder(String cpu, String memory) {
this.cpu = validateRequired(cpu, "CPU不能为空");
this.memory = validateRequired(memory, "内存不能为空");
}
/**
* 设置存储设备
*/
public Builder storage(String storage) {
this.storage = validateRequired(storage, "存储设备不能为空");
return this;
}
/**
* 设置显卡
*/
public Builder graphicsCard(String graphicsCard) {
this.graphicsCard = validateRequired(graphicsCard, "显卡不能为空");
return this;
}
/**
* 设置主板
*/
public Builder motherboard(String motherboard) {
this.motherboard = validateRequired(motherboard, "主板不能为空");
return this;
}
/**
* 设置电源
*/
public Builder powerSupply(String powerSupply) {
this.powerSupply = validateRequired(powerSupply, "电源不能为空");
return this;
}
/**
* 设置机箱
*/
public Builder computerCase(String computerCase) {
this.computerCase = validateRequired(computerCase, "机箱不能为空");
return this;
}
/**
* 设置WiFi功能
*/
public Builder withWifi() {
this.hasWifi = true;
return this;
}
/**
* 设置蓝牙功能
*/
public Builder withBluetooth() {
this.hasBluetooth = true;
return this;
}
/**
* 设置无线功能(WiFi + 蓝牙)
*/
public Builder withWireless() {
this.hasWifi = true;
this.hasBluetooth = true;
return this;
}
/**
* 构建Computer对象
*/
public Computer build() {
// 构建前验证
validateConfiguration();
return new Computer(this);
}
/**
* 参数验证
*/
private String validateRequired(String value, String message) {
if (value == null || value.trim().isEmpty()) {
throw new IllegalArgumentException(message);
}
return value.trim();
}
/**
* 配置验证
*/
private void validateConfiguration() {
// 验证CPU和内存的兼容性
if (cpu.contains("Intel") && memory.contains("DDR5")) {
// 检查Intel CPU是否支持DDR5
System.out.println("验证Intel CPU与DDR5内存兼容性");
}
// 验证电源功率是否足够
if (graphicsCard.contains("RTX") && !powerSupply.contains("750W")) {
System.out.println("警告:高端显卡建议使用750W以上电源");
}
}
}
/**
* 显示计算机配置
*/
public void displayConfiguration() {
System.out.println("\n=== 计算机配置信息 ===");
System.out.println("CPU: " + cpu);
System.out.println("内存: " + memory);
System.out.println("存储: " + storage);
System.out.println("显卡: " + graphicsCard);
System.out.println("主板: " + motherboard);
System.out.println("电源: " + powerSupply);
System.out.println("机箱: " + computerCase);
System.out.println("WiFi: " + (hasWifi ? "支持" : "不支持"));
System.out.println("蓝牙: " + (hasBluetooth ? "支持" : "不支持"));
}
/**
* 计算总价格(示例)
*/
public double calculatePrice() {
double basePrice = 3000.0; // 基础价格
// 根据配置计算价格
if (cpu.contains("i9") || cpu.contains("Ryzen 9")) {
basePrice += 2000;
} else if (cpu.contains("i7") || cpu.contains("Ryzen 7")) {
basePrice += 1000;
}
if (memory.contains("32GB")) {
basePrice += 800;
} else if (memory.contains("16GB")) {
basePrice += 400;
}
if (graphicsCard.contains("RTX")) {
basePrice += 3000;
}
if (hasWifi) basePrice += 100;
if (hasBluetooth) basePrice += 50;
return basePrice;
}
// Getters
public String getCpu() { return cpu; }
public String getMemory() { return memory; }
public String getStorage() { return storage; }
public String getGraphicsCard() { return graphicsCard; }
public String getMotherboard() { return motherboard; }
public String getPowerSupply() { return powerSupply; }
public String getComputerCase() { return computerCase; }
public boolean hasWifi() { return hasWifi; }
public boolean hasBluetooth() { return hasBluetooth; }
}
5.3 高级建造者模式
5.3.1 导演者模式(Director Pattern)
/**
* 导演者类 - 封装构建过程
*/
public class ComputerDirector {
/**
* 构建游戏电脑
*/
public Computer buildGamingComputer() {
return new Computer.Builder("Intel i9-13900K", "32GB DDR5")
.storage("1TB NVMe SSD")
.graphicsCard("RTX 4080")
.motherboard("Z790 Gaming主板")
.powerSupply("850W 80+ Gold")
.computerCase("RGB游戏机箱")
.withWireless()
.build();
}
/**
* 构建办公电脑
*/
public Computer buildOfficeComputer() {
return new Computer.Builder("Intel i5-13400", "16GB DDR4")
.storage("512GB SSD")
.graphicsCard("集成显卡")
.motherboard("B660商务主板")
.powerSupply("500W 80+ Bronze")
.computerCase("静音办公机箱")
.withWifi()
.build();
}
/**
* 构建服务器
*/
public Computer buildServerComputer() {
return new Computer.Builder("AMD EPYC 7763", "128GB ECC DDR4")
.storage("2TB NVMe SSD RAID")
.graphicsCard("无显卡")
.motherboard("服务器主板")
.powerSupply("1200W 80+ Platinum")
.computerCase("4U机架式机箱")
.build();
}
/**
* 构建预算电脑
*/
public Computer buildBudgetComputer() {
return new Computer.Builder("AMD Ryzen 5 5600G", "8GB DDR4")
.storage("256GB SSD")
.graphicsCard("集成显卡")
.motherboard("A520主板")
.powerSupply("400W")
.computerCase("标准机箱")
.build();
}
}
5.3.2 流式建造者模式
/**
* 流式建造者模式 - SQL查询构建器
*/
public class SQLQueryBuilder {
private StringBuilder query;
private String tableName;
private List<String> selectFields;
private List<String> whereConditions;
private List<String> joinClauses;
private String orderBy;
private String groupBy;
private String having;
private Integer limit;
public SQLQueryBuilder() {
this.query = new StringBuilder();
this.selectFields = new ArrayList<>();
this.whereConditions = new ArrayList<>();
this.joinClauses = new ArrayList<>();
}
/**
* SELECT子句
*/
public SQLQueryBuilder select(String... fields) {
Collections.addAll(selectFields, fields);
return this;
}
/**
* FROM子句
*/
public SQLQueryBuilder from(String tableName) {
this.tableName = tableName;
return this;
}
/**
* WHERE子句
*/
public SQLQueryBuilder where(String condition) {
whereConditions.add(condition);
return this;
}
/**
* AND条件
*/
public SQLQueryBuilder and(String condition) {
if (!whereConditions.isEmpty()) {
whereConditions.add("AND " + condition);
} else {
whereConditions.add(condition);
}
return this;
}
/**
* OR条件
*/
public SQLQueryBuilder or(String condition) {
if (!whereConditions.isEmpty()) {
whereConditions.add("OR " + condition);
} else {
whereConditions.add(condition);
}
return this;
}
/**
* JOIN子句
*/
public SQLQueryBuilder join(String table, String condition) {
joinClauses.add("JOIN " + table + " ON " + condition);
return this;
}
/**
* LEFT JOIN子句
*/
public SQLQueryBuilder leftJoin(String table, String condition) {
joinClauses.add("LEFT JOIN " + table + " ON " + condition);
return this;
}
/**
* ORDER BY子句
*/
public SQLQueryBuilder orderBy(String orderBy) {
this.orderBy = orderBy;
return this;
}
/**
* GROUP BY子句
*/
public SQLQueryBuilder groupBy(String groupBy) {
this.groupBy = groupBy;
return this;
}
/**
* HAVING子句
*/
public SQLQueryBuilder having(String having) {
this.having = having;
return this;
}
/**
* LIMIT子句
*/
public SQLQueryBuilder limit(int limit) {
this.limit = limit;
return this;
}
/**
* 构建SQL查询
*/
public String build() {
if (tableName == null) {
throw new IllegalStateException("表名不能为空");
}
StringBuilder sql = new StringBuilder();
// SELECT子句
sql.append("SELECT ");
if (selectFields.isEmpty()) {
sql.append("*");
} else {
sql.append(String.join(", ", selectFields));
}
// FROM子句
sql.append(" FROM ").append(tableName);
// JOIN子句
for (String join : joinClauses) {
sql.append(" ").append(join);
}
// WHERE子句
if (!whereConditions.isEmpty()) {
sql.append(" WHERE ").append(String.join(" ", whereConditions));
}
// GROUP BY子句
if (groupBy != null) {
sql.append(" GROUP BY ").append(groupBy);
}
// HAVING子句
if (having != null) {
sql.append(" HAVING ").append(having);
}
// ORDER BY子句
if (orderBy != null) {
sql.append(" ORDER BY ").append(orderBy);
}
// LIMIT子句
if (limit != null) {
sql.append(" LIMIT ").append(limit);
}
return sql.toString();
}
/**
* 重置建造者
*/
public SQLQueryBuilder reset() {
this.query = new StringBuilder();
this.tableName = null;
this.selectFields.clear();
this.whereConditions.clear();
this.joinClauses.clear();
this.orderBy = null;
this.groupBy = null;
this.having = null;
this.limit = null;
return this;
}
}
5.4 建造者模式的优缺点
优点:
- 参数灵活:支持可选参数和默认值
- 链式调用:提供流畅的API接口
- 参数验证:在构建过程中进行校验
- 不可变对象:构建完成后对象状态不可改变
- 可读性好:代码清晰易懂
缺点:
- 代码冗长:需要编写大量的建造者代码
- 内存开销:创建额外的建造者对象
- 复杂性增加:增加了类的数量和复杂度
使用场景:
- 复杂对象创建:对象有多个可选参数
- 参数验证:需要在创建过程中进行复杂验证
- 不可变对象:需要创建不可变的对象
- 配置对象:系统配置、数据库连接配置等
6. 原型模式(Prototype Pattern)
6.1 模式定义
原型模式用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。它允许一个对象再创建另外一个可定制的对象,而无需知道任何如何创建的细节。
核心思想:
- 对象克隆:通过复制现有对象来创建新对象
- 避免重复初始化:减少对象创建的开销
- 动态配置:运行时确定要创建的对象类型
- 深拷贝与浅拷贝:根据需要选择合适的拷贝方式
6.2 基本实现
/**
* 原型模式实现 - 图形编辑器
*/
/**
* 抽象原型接口
*/
public interface Prototype extends Cloneable {
Prototype clone();
void draw();
String getInfo();
}
/**
* 具体原型 - 圆形
*/
public class Circle implements Prototype {
private int x, y, radius;
private String color;
private String fillStyle;
public Circle(int x, int y, int radius, String color, String fillStyle) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.fillStyle = fillStyle;
// 模拟复杂的初始化过程
System.out.println("创建圆形对象 - 执行复杂初始化...");
simulateComplexInitialization();
}
/**
* 拷贝构造函数
*/
private Circle(Circle other) {
this.x = other.x;
this.y = other.y;
this.radius = other.radius;
this.color = other.color;
this.fillStyle = other.fillStyle;
System.out.println("通过原型克隆圆形对象 - 跳过复杂初始化");
}
@Override
public Prototype clone() {
return new Circle(this);
}
@Override
public void draw() {
System.out.println(String.format(
"绘制圆形: 位置(%d,%d), 半径=%d, 颜色=%s, 填充=%s",
x, y, radius, color, fillStyle));
}
@Override
public String getInfo() {
return String.format("Circle[x=%d, y=%d, radius=%d, color=%s, fill=%s]",
x, y, radius, color, fillStyle);
}
/**
* 模拟复杂的初始化过程
*/
private void simulateComplexInitialization() {
try {
Thread.sleep(100); // 模拟耗时操作
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// Setters for modification
public void setPosition(int x, int y) {
this.x = x;
this.y = y;
}
public void setRadius(int radius) {
this.radius = radius;
}
public void setColor(String color) {
this.color = color;
}
public void setFillStyle(String fillStyle) {
this.fillStyle = fillStyle;
}
}
/**
* 具体原型 - 矩形
*/
public class Rectangle implements Prototype {
private int x, y, width, height;
private String color;
private String borderStyle;
private int borderWidth;
public Rectangle(int x, int y, int width, int height,
String color, String borderStyle, int borderWidth) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.color = color;
this.borderStyle = borderStyle;
this.borderWidth = borderWidth;
System.out.println("创建矩形对象 - 执行复杂初始化...");
simulateComplexInitialization();
}
/**
* 拷贝构造函数
*/
private Rectangle(Rectangle other) {
this.x = other.x;
this.y = other.y;
this.width = other.width;
this.height = other.height;
this.color = other.color;
this.borderStyle = other.borderStyle;
this.borderWidth = other.borderWidth;
System.out.println("通过原型克隆矩形对象 - 跳过复杂初始化");
}
@Override
public Prototype clone() {
return new Rectangle(this);
}
@Override
public void draw() {
System.out.println(String.format(
"绘制矩形: 位置(%d,%d), 尺寸=%dx%d, 颜色=%s, 边框=%s(%dpx)",
x, y, width, height, color, borderStyle, borderWidth));
}
@Override
public String getInfo() {
return String.format("Rectangle[x=%d, y=%d, w=%d, h=%d, color=%s, border=%s]",
x, y, width, height, color, borderStyle);
}
private void simulateComplexInitialization() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// Setters for modification
public void setPosition(int x, int y) {
this.x = x;
this.y = y;
}
public void setSize(int width, int height) {
this.width = width;
this.height = height;
}
public void setColor(String color) {
this.color = color;
}
public void setBorderStyle(String borderStyle, int borderWidth) {
this.borderStyle = borderStyle;
this.borderWidth = borderWidth;
}
}
6.3 原型管理器
/**
* 原型管理器 - 管理和缓存原型对象
*/
public class PrototypeManager {
private Map<String, Prototype> prototypes = new HashMap<>();
/**
* 注册原型
*/
public void registerPrototype(String key, Prototype prototype) {
prototypes.put(key, prototype);
System.out.println("注册原型: " + key + " -> " + prototype.getInfo());
}
/**
* 获取原型克隆
*/
public Prototype getPrototype(String key) {
Prototype prototype = prototypes.get(key);
if (prototype == null) {
throw new IllegalArgumentException("未找到原型: " + key);
}
return prototype.clone();
}
/**
* 移除原型
*/
public void removePrototype(String key) {
Prototype removed = prototypes.remove(key);
if (removed != null) {
System.out.println("移除原型: " + key);
}
}
/**
* 列出所有原型
*/
public void listPrototypes() {
System.out.println("\n=== 已注册的原型 ===");
prototypes.forEach((key, prototype) -> {
System.out.println(key + ": " + prototype.getInfo());
});
}
/**
* 批量创建对象
*/
public List<Prototype> createMultiple(String key, int count) {
List<Prototype> objects = new ArrayList<>();
for (int i = 0; i < count; i++) {
objects.add(getPrototype(key));
}
return objects;
}
}
/**
* 图形编辑器 - 使用原型模式
*/
public class GraphicsEditor {
private PrototypeManager prototypeManager;
private List<Prototype> canvas;
public GraphicsEditor() {
this.prototypeManager = new PrototypeManager();
this.canvas = new ArrayList<>();
initializePrototypes();
}
/**
* 初始化预定义原型
*/
private void initializePrototypes() {
System.out.println("\n=== 初始化图形原型 ===");
// 注册常用图形原型
prototypeManager.registerPrototype("default-circle",
new Circle(0, 0, 50, "blue", "solid"));
prototypeManager.registerPrototype("default-rectangle",
new Rectangle(0, 0, 100, 80, "red", "solid", 2));
prototypeManager.registerPrototype("large-circle",
new Circle(0, 0, 100, "green", "gradient"));
prototypeManager.registerPrototype("small-rectangle",
new Rectangle(0, 0, 50, 30, "yellow", "dashed", 1));
}
/**
* 添加图形到画布
*/
public void addShape(String prototypeKey, int x, int y) {
try {
Prototype shape = prototypeManager.getPrototype(prototypeKey);
// 根据类型设置位置
if (shape instanceof Circle) {
((Circle) shape).setPosition(x, y);
} else if (shape instanceof Rectangle) {
((Rectangle) shape).setPosition(x, y);
}
canvas.add(shape);
System.out.println("添加图形到画布: " + shape.getInfo());
} catch (IllegalArgumentException e) {
System.err.println("错误: " + e.getMessage());
}
}
/**
* 批量添加图形
*/
public void addMultipleShapes(String prototypeKey, int count) {
System.out.println("\n批量创建 " + count + " 个 " + prototypeKey + " 图形:");
long startTime = System.currentTimeMillis();
List<Prototype> shapes = prototypeManager.createMultiple(prototypeKey, count);
long endTime = System.currentTimeMillis();
// 随机设置位置
Random random = new Random();
for (Prototype shape : shapes) {
int x = random.nextInt(500);
int y = random.nextInt(500);
if (shape instanceof Circle) {
((Circle) shape).setPosition(x, y);
} else if (shape instanceof Rectangle) {
((Rectangle) shape).setPosition(x, y);
}
canvas.add(shape);
}
System.out.println("批量创建完成,耗时: " + (endTime - startTime) + "ms");
}
/**
* 渲染画布
*/
public void renderCanvas() {
System.out.println("\n=== 渲染画布 (" + canvas.size() + " 个图形) ===");
for (int i = 0; i < canvas.size(); i++) {
System.out.print((i + 1) + ". ");
canvas.get(i).draw();
}
}
/**
* 清空画布
*/
public void clearCanvas() {
canvas.clear();
System.out.println("画布已清空");
}
/**
* 显示原型列表
*/
public void showPrototypes() {
prototypeManager.listPrototypes();
}
}
6.4 深拷贝与浅拷贝
/**
* 深拷贝示例 - 复杂图形对象
*/
public class ComplexShape implements Prototype {
private String name;
private List<Point> points;
private Style style;
private Map<String, Object> properties;
public ComplexShape(String name) {
this.name = name;
this.points = new ArrayList<>();
this.style = new Style();
this.properties = new HashMap<>();
}
/**
* 深拷贝构造函数
*/
private ComplexShape(ComplexShape other) {
this.name = other.name;
// 深拷贝点列表
this.points = new ArrayList<>();
for (Point point : other.points) {
this.points.add(new Point(point));
}
// 深拷贝样式对象
this.style = new Style(other.style);
// 深拷贝属性映射
this.properties = new HashMap<>();
for (Map.Entry<String, Object> entry : other.properties.entrySet()) {
Object value = entry.getValue();
if (value instanceof Cloneable) {
// 如果值是可克隆的,进行深拷贝
this.properties.put(entry.getKey(), deepClone(value));
} else {
// 否则进行浅拷贝
this.properties.put(entry.getKey(), value);
}
}
}
@Override
public Prototype clone() {
return new ComplexShape(this);
}
@Override
public void draw() {
System.out.println("绘制复杂图形: " + name);
System.out.println(" 点数量: " + points.size());
System.out.println(" 样式: " + style);
System.out.println(" 属性: " + properties.size() + " 个");
}
@Override
public String getInfo() {
return String.format("ComplexShape[name=%s, points=%d, style=%s]",
name, points.size(), style);
}
/**
* 深拷贝辅助方法
*/
private Object deepClone(Object obj) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return ois.readObject();
} catch (Exception e) {
throw new RuntimeException("深拷贝失败", e);
}
}
// 辅助类
public static class Point {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point(Point other) {
this.x = other.x;
this.y = other.y;
}
@Override
public String toString() {
return String.format("(%d,%d)", x, y);
}
}
public static class Style {
private String color;
private int thickness;
public Style() {
this.color = "black";
this.thickness = 1;
}
public Style(Style other) {
this.color = other.color;
this.thickness = other.thickness;
}
@Override
public String toString() {
return String.format("Style[color=%s, thickness=%d]", color, thickness);
}
}
// 添加点
public void addPoint(int x, int y) {
points.add(new Point(x, y));
}
// 设置样式
public void setStyle(String color, int thickness) {
style.color = color;
style.thickness = thickness;
}
// 设置属性
public void setProperty(String key, Object value) {
properties.put(key, value);
}
}
6.5 原型模式的优缺点
优点:
- 性能优化:避免重复的复杂初始化过程
- 动态配置:运行时确定要创建的对象类型
- 简化创建:无需知道具体类就能创建对象
- 保护原型:原型对象不会被修改
缺点:
- 深拷贝复杂:包含循环引用时实现困难
- 克隆方法维护:每个类都需要实现克隆方法
- 内存开销:需要维护原型对象
使用场景:
- 对象创建成本高:初始化过程复杂或耗时
- 动态对象创建:运行时确定对象类型
- 对象状态相似:需要创建大量相似对象
- 避免工厂层次:简化复杂的工厂继承体系
本章小结:
创建型设计模式为对象创建提供了灵活而强大的解决方案。单例模式确保全局唯一实例,适用于配置管理、日志记录等场景。工厂方法模式通过继承来决定创建哪种产品,提供了良好的扩展性。抽象工厂模式进一步扩展了工厂方法模式,用于创建产品族,确保相关产品的一致性。建造者模式将复杂对象的构建过程分解为多个步骤,提供了流畅的API和参数验证。原型模式通过克隆现有对象来创建新对象,避免了重复的初始化过程。
这些模式都遵循面向对象设计原则,能够有效地解决对象创建过程中的复杂性问题。在实际应用中,我们需要根据具体需求选择合适的创建型模式,避免过度设计。同时要注意线程安全、性能优化等实际问题,确保模式的正确实现和高效运行。
7. 创建型模式综合应用
7.1 模式组合使用
在实际项目中,创建型模式往往不是单独使用,而是组合使用以解决复杂的对象创建问题。
/**
* 创建型模式综合应用 - 游戏引擎
*/
/**
* 游戏对象工厂 - 结合抽象工厂和原型模式
*/
public abstract class GameObjectFactory {
protected PrototypeManager prototypeManager;
public GameObjectFactory() {
this.prototypeManager = new PrototypeManager();
initializePrototypes();
}
/**
* 初始化原型对象
*/
protected abstract void initializePrototypes();
/**
* 创建角色
*/
public abstract GameObject createCharacter(String type);
/**
* 创建武器
*/
public abstract GameObject createWeapon(String type);
/**
* 创建道具
*/
public abstract GameObject createItem(String type);
/**
* 批量创建对象
*/
public List<GameObject> createMultiple(String type, int count) {
List<GameObject> objects = new ArrayList<>();
for (int i = 0; i < count; i++) {
GameObject obj = prototypeManager.getPrototype(type);
if (obj != null) {
objects.add(obj);
}
}
return objects;
}
}
/**
* 奇幻游戏对象工厂
*/
public class FantasyGameObjectFactory extends GameObjectFactory {
@Override
protected void initializePrototypes() {
// 注册角色原型
prototypeManager.registerPrototype("warrior",
new FantasyCharacter("战士", 100, 20, "剑盾"));
prototypeManager.registerPrototype("mage",
new FantasyCharacter("法师", 60, 40, "法杖"));
prototypeManager.registerPrototype("archer",
new FantasyCharacter("弓箭手", 80, 30, "弓箭"));
// 注册武器原型
prototypeManager.registerPrototype("sword",
new FantasyWeapon("长剑", 25, "近战"));
prototypeManager.registerPrototype("staff",
new FantasyWeapon("法杖", 35, "魔法"));
prototypeManager.registerPrototype("bow",
new FantasyWeapon("精灵弓", 30, "远程"));
// 注册道具原型
prototypeManager.registerPrototype("health-potion",
new FantasyItem("生命药水", "恢复50点生命值", 50));
prototypeManager.registerPrototype("mana-potion",
new FantasyItem("魔法药水", "恢复30点魔法值", 30));
}
@Override
public GameObject createCharacter(String type) {
return prototypeManager.getPrototype(type);
}
@Override
public GameObject createWeapon(String type) {
return prototypeManager.getPrototype(type);
}
@Override
public GameObject createItem(String type) {
return prototypeManager.getPrototype(type);
}
}
/**
* 游戏配置管理器 - 单例模式
*/
public class GameConfigManager {
private static volatile GameConfigManager instance;
private Properties gameConfig;
private Map<String, GameObjectFactory> factories;
private GameConfigManager() {
this.gameConfig = new Properties();
this.factories = new HashMap<>();
loadConfiguration();
initializeFactories();
}
public static GameConfigManager getInstance() {
if (instance == null) {
synchronized (GameConfigManager.class) {
if (instance == null) {
instance = new GameConfigManager();
}
}
}
return instance;
}
/**
* 加载游戏配置
*/
private void loadConfiguration() {
// 模拟从配置文件加载
gameConfig.setProperty("game.type", "fantasy");
gameConfig.setProperty("max.players", "100");
gameConfig.setProperty("world.size", "1000x1000");
gameConfig.setProperty("difficulty", "normal");
}
/**
* 初始化工厂
*/
private void initializeFactories() {
factories.put("fantasy", new FantasyGameObjectFactory());
// 可以添加更多游戏类型的工厂
// factories.put("scifi", new SciFiGameObjectFactory());
// factories.put("modern", new ModernGameObjectFactory());
}
/**
* 获取游戏对象工厂
*/
public GameObjectFactory getGameObjectFactory() {
String gameType = gameConfig.getProperty("game.type", "fantasy");
return factories.get(gameType);
}
/**
* 获取配置值
*/
public String getConfig(String key) {
return gameConfig.getProperty(key);
}
/**
* 设置配置值
*/
public void setConfig(String key, String value) {
gameConfig.setProperty(key, value);
}
}
/**
* 游戏世界建造者 - 建造者模式
*/
public class GameWorld {
private final String name;
private final int width;
private final int height;
private final String theme;
private final List<GameObject> npcs;
private final List<GameObject> items;
private final List<GameObject> obstacles;
private final String backgroundMusic;
private final String weatherEffect;
private GameWorld(Builder builder) {
this.name = builder.name;
this.width = builder.width;
this.height = builder.height;
this.theme = builder.theme;
this.npcs = new ArrayList<>(builder.npcs);
this.items = new ArrayList<>(builder.items);
this.obstacles = new ArrayList<>(builder.obstacles);
this.backgroundMusic = builder.backgroundMusic;
this.weatherEffect = builder.weatherEffect;
}
public static class Builder {
private final String name;
private final int width;
private final int height;
private String theme = "default";
private List<GameObject> npcs = new ArrayList<>();
private List<GameObject> items = new ArrayList<>();
private List<GameObject> obstacles = new ArrayList<>();
private String backgroundMusic = "default.mp3";
private String weatherEffect = "none";
public Builder(String name, int width, int height) {
this.name = name;
this.width = width;
this.height = height;
}
public Builder theme(String theme) {
this.theme = theme;
return this;
}
public Builder addNPC(GameObject npc) {
this.npcs.add(npc);
return this;
}
public Builder addNPCs(List<GameObject> npcs) {
this.npcs.addAll(npcs);
return this;
}
public Builder addItem(GameObject item) {
this.items.add(item);
return this;
}
public Builder addItems(List<GameObject> items) {
this.items.addAll(items);
return this;
}
public Builder addObstacle(GameObject obstacle) {
this.obstacles.add(obstacle);
return this;
}
public Builder backgroundMusic(String music) {
this.backgroundMusic = music;
return this;
}
public Builder weatherEffect(String weather) {
this.weatherEffect = weather;
return this;
}
public GameWorld build() {
validateWorld();
return new GameWorld(this);
}
private void validateWorld() {
if (name == null || name.trim().isEmpty()) {
throw new IllegalArgumentException("世界名称不能为空");
}
if (width <= 0 || height <= 0) {
throw new IllegalArgumentException("世界尺寸必须大于0");
}
}
}
public void displayWorldInfo() {
System.out.println("\n=== 游戏世界信息 ===");
System.out.println("名称: " + name);
System.out.println("尺寸: " + width + "x" + height);
System.out.println("主题: " + theme);
System.out.println("NPC数量: " + npcs.size());
System.out.println("道具数量: " + items.size());
System.out.println("障碍物数量: " + obstacles.size());
System.out.println("背景音乐: " + backgroundMusic);
System.out.println("天气效果: " + weatherEffect);
}
// Getters
public String getName() { return name; }
public int getWidth() { return width; }
public int getHeight() { return height; }
public String getTheme() { return theme; }
public List<GameObject> getNpcs() { return new ArrayList<>(npcs); }
public List<GameObject> getItems() { return new ArrayList<>(items); }
public List<GameObject> getObstacles() { return new ArrayList<>(obstacles); }
}
7.2 性能优化策略
/**
* 对象池 - 优化对象创建性能
*/
public class GameObjectPool {
private Map<String, Queue<GameObject>> pools;
private GameObjectFactory factory;
private int maxPoolSize;
public GameObjectPool(GameObjectFactory factory, int maxPoolSize) {
this.factory = factory;
this.maxPoolSize = maxPoolSize;
this.pools = new ConcurrentHashMap<>();
}
/**
* 获取对象
*/
public GameObject getObject(String type) {
Queue<GameObject> pool = pools.computeIfAbsent(type,
k -> new ConcurrentLinkedQueue<>());
GameObject obj = pool.poll();
if (obj == null) {
// 池中没有可用对象,创建新对象
if ("warrior".equals(type) || "mage".equals(type) || "archer".equals(type)) {
obj = factory.createCharacter(type);
} else if ("sword".equals(type) || "staff".equals(type) || "bow".equals(type)) {
obj = factory.createWeapon(type);
} else {
obj = factory.createItem(type);
}
}
return obj;
}
/**
* 归还对象到池中
*/
public void returnObject(String type, GameObject obj) {
if (obj == null) return;
Queue<GameObject> pool = pools.computeIfAbsent(type,
k -> new ConcurrentLinkedQueue<>());
if (pool.size() < maxPoolSize) {
// 重置对象状态
obj.reset();
pool.offer(obj);
}
// 如果池已满,让对象被垃圾回收
}
/**
* 预热对象池
*/
public void warmUp(String type, int count) {
for (int i = 0; i < count; i++) {
GameObject obj = getObject(type);
returnObject(type, obj);
}
}
/**
* 获取池状态
*/
public void printPoolStatus() {
System.out.println("\n=== 对象池状态 ===");
pools.forEach((type, pool) -> {
System.out.println(type + ": " + pool.size() + " 个可用对象");
});
}
}
8. 实践练习
8.1 基础练习
练习1:日志系统设计
要求:
- 使用单例模式设计一个日志管理器
- 支持多种日志级别(DEBUG、INFO、WARN、ERROR)
- 支持多种输出方式(控制台、文件、数据库)
- 确保线程安全
练习2:图形编辑器
要求:
- 使用工厂方法模式创建不同类型的图形(圆形、矩形、三角形)
- 使用原型模式实现图形的复制功能
- 支持图形的基本操作(移动、缩放、旋转)
练习3:数据库连接管理
要求:
- 使用抽象工厂模式支持多种数据库(MySQL、PostgreSQL、Oracle)
- 为每种数据库提供连接、命令、事务对象
- 使用建造者模式构建复杂的SQL查询
8.2 进阶练习
练习4:电商系统订单处理
要求:
- 使用建造者模式创建复杂的订单对象
- 订单包含:商品列表、收货地址、支付方式、优惠券、配送选项
- 支持订单验证和价格计算
- 实现订单的序列化和反序列化
练习5:游戏角色系统
要求:
- 结合多种创建型模式设计角色系统
- 使用工厂模式创建不同职业的角色
- 使用建造者模式配置角色属性和装备
- 使用原型模式实现角色模板和复制
- 使用单例模式管理全局游戏配置
8.3 综合项目
项目:微服务配置中心
功能要求:
- 配置管理:支持多环境配置(开发、测试、生产)
- 服务发现:动态注册和发现微服务
- 负载均衡:支持多种负载均衡策略
- 配置热更新:支持配置的动态更新
- 监控告警:提供配置变更监控和告警
设计要求:
- 使用单例模式管理配置中心实例
- 使用工厂模式创建不同类型的配置源
- 使用建造者模式构建复杂的服务配置
- 使用原型模式实现配置模板
- 考虑线程安全和性能优化
9. 总结
9.1 创建型模式对比
模式 | 主要目的 | 适用场景 | 优点 | 缺点 |
---|---|---|---|---|
单例模式 | 确保唯一实例 | 全局配置、日志管理 | 节省内存、全局访问 | 难以测试、违反单一职责 |
工厂方法 | 创建产品对象 | 对象类型运行时确定 | 符合开闭原则、解耦 | 增加类的数量 |
抽象工厂 | 创建产品族 | 多个相关产品 | 保证产品一致性 | 扩展困难 |
建造者 | 构建复杂对象 | 多参数对象创建 | 参数灵活、链式调用 | 代码冗长 |
原型 | 克隆对象 | 对象创建成本高 | 性能优化、动态配置 | 深拷贝复杂 |
9.2 选择指南
选择创建型模式的决策树:
9.3 最佳实践
- 避免过度设计:不要为了使用模式而使用模式
- 考虑性能影响:某些模式可能带来性能开销
- 保持代码简洁:模式应该简化而不是复杂化代码
- 注意线程安全:多线程环境下要特别注意
- 文档化设计决策:记录为什么选择特定模式
9.4 发展趋势
- 依赖注入框架:Spring、Guice等框架简化了对象创建
- 函数式编程:Lambda表达式和函数式接口提供新的创建方式
- 注解驱动:通过注解简化配置和对象创建
- 云原生架构:微服务和容器化对对象创建提出新要求
9.5 下一步学习
- 深入学习结构型模式:适配器、装饰器、代理等模式
- 掌握行为型模式:观察者、策略、命令等模式
- 学习架构模式:MVC、MVP、MVVM等架构模式
- 实践项目应用:在实际项目中应用设计模式
- 阅读优秀源码:分析开源框架中的模式应用
预计阅读时间:5小时
实践时间:8-12小时
难度等级:🟡 中级
前置知识:面向对象编程基础、Java语言基础、设计模式概述
实践练习
练习1:单例模式实现
实现一个线程安全的单例模式:
- 使用懒汉式实现单例模式
- 使用饿汉式实现单例模式
- 使用双重检查锁定实现单例模式
- 使用枚举实现单例模式
- 比较各种实现方式的优缺点
- 编写测试代码验证线程安全性
练习2:工厂模式应用
设计一个图形绘制系统:
- 定义图形接口(Shape)
- 实现具体图形类(Circle、Rectangle、Triangle)
- 实现简单工厂模式创建图形
- 扩展为工厂方法模式
- 进一步扩展为抽象工厂模式
- 分析各种工厂模式的适用场景
练习3:建造者模式实践
设计一个复杂对象的构建系统:
- 选择一个复杂对象(如汽车、电脑配置等)
- 分析对象的组成部分和构建步骤
- 实现建造者模式
- 提供多种具体建造者
- 实现指挥者类
- 测试不同配置的对象构建
练习4:原型模式应用
实现一个文档克隆系统:
- 设计文档类层次结构
- 实现浅克隆和深克隆
- 处理复杂对象的克隆
- 实现原型管理器
- 测试克隆的正确性
- 分析原型模式的性能优势
常见问题
Q: 什么时候应该使用创建型设计模式?
A: 在以下情况下考虑使用创建型模式:
- 系统需要独立于对象的创建、组合和表示
- 需要配置具有多个产品系列之一的系统
- 需要强调一系列相关产品对象的设计
- 想要提供一个产品类库,只显示接口而不显示实现
- 对象的创建过程复杂或需要大量配置
Q: 单例模式有什么缺点?
A: 单例模式的主要缺点包括:
- 违反了单一职责原则(既管理实例又处理业务逻辑)
- 增加了代码的耦合度
- 在多线程环境下需要特别处理
- 难于进行单元测试
- 可能成为系统的瓶颈
- 在某些情况下违反了开闭原则
Q: 工厂方法模式和抽象工厂模式有什么区别?
A: 主要区别包括:
- 工厂方法模式:创建一个产品,关注单个产品的创建
- 抽象工厂模式:创建一系列相关产品,关注产品族的创建
- 复杂度:抽象工厂模式更复杂,涉及多个产品等级结构
- 扩展性:工厂方法更容易扩展新产品,抽象工厂更容易扩展新产品族
Q: 建造者模式和工厂模式有什么区别?
A: 主要区别在于:
- 关注点:工厂模式关注创建什么,建造者模式关注如何创建
- 复杂度:建造者模式适用于创建复杂对象,工厂模式适用于简单对象
- 构建过程:建造者模式强调分步骤构建,工厂模式一次性创建
- 产品变化:建造者模式产品内部结构复杂多变,工厂模式产品相对简单
Q: 原型模式什么时候比直接创建对象更有优势?
A: 在以下情况下原型模式更有优势:
- 对象的创建成本很高(如需要大量计算或网络请求)
- 需要创建大量相似对象
- 对象的初始化需要复杂的配置
- 需要避免与具体类的耦合
- 系统需要独立于产品的创建、组合和表示
Q: 如何选择合适的创建型模式?
A: 选择建议:
- 单例模式:确保全局只有一个实例
- 工厂方法:创建单一产品,需要灵活扩展
- 抽象工厂:创建产品族,需要保证产品一致性
- 建造者模式:创建复杂对象,构建过程稳定
- 原型模式:创建成本高,需要大量相似对象
总结
创建型设计模式是面向对象设计的重要组成部分,通过本章学习,您应该掌握:
- 模式理解:深入理解五种创建型模式的核心思想和适用场景
- 实现技能:能够根据需求选择和实现合适的创建型模式
- 设计思维:具备将创建逻辑与业务逻辑分离的设计思维
- 质量意识:注重代码的可维护性、可扩展性和可测试性
- 实践能力:能够在实际项目中灵活运用这些模式
创建型模式的核心价值在于将对象的创建和使用分离,提高系统的灵活性和可维护性。掌握这些模式将显著提升您的面向对象设计能力。
参考与引用
- 《设计模式:可复用面向对象软件的基础》- GoF著 (1995)
- 《Head First设计模式》- Eric Freeman等著 (2004)
- 《设计模式解析》- Alan Shalloway等著 (2004)
- Java设计模式官方教程
- 《重构:改善既有代码的设计》- Martin Fowler著 (2018)
- 《软件设计师教程》(第5版)- 清华大学出版社 (2020)
- 设计模式在线参考
更新记录
更新时间 | 版本 | 更新内容 | 更新人 |
---|---|---|---|
2024-12-19 | v1.0.0 | 初始版本创建,创建型设计模式详解 | 教程团队 |
2024-12-19 | v1.0.1 | 添加实践练习、常见问题、总结、参考引用等完整结构 | 教程团队 |