设计模式
Java设计模式通常指GoF(四人组)提出的23种经典模式,按目的可分为
- 创建型(5种)
- 结构型(7种)
- 行为型(11种)
三大类
创建型模式(5种)
单例模式 (Singleton)
场景:全局配置管理器、数据库连接池
// 懒汉式 - 双重检查锁(最推荐)
public class ConfigManager {
private static volatile ConfigManager instance;
private ConfigManager() {
// 私有构造,防止外部new
loadConfig();
}
public static ConfigManager getInstance() {
if (instance == null) {
synchronized (ConfigManager.class) {
if (instance == null) {
instance = new ConfigManager();
}
}
}
return instance;
}
private void loadConfig() {
System.out.println("加载配置文件...");
}
public String getProperty(String key) {
return "value_of_" + key;
}
}
// 使用
ConfigManager config = ConfigManager.getInstance();
String dbUrl = config.getProperty("db.url");
工厂方法模式 (Factory Method)
场景:不同渠道生成不同格式的日志
// 产品接口
interface Logger {
void log(String message);
}
// 具体产品
class FileLogger implements Logger {
@Override
public void log(String message) {
System.out.println("写入文件日志: " + message);
}
}
class ConsoleLogger implements Logger {
@Override
public void log(String message) {
System.out.println("控制台输出: " + message);
}
}
// 抽象工厂
abstract class LoggerFactory {
public abstract Logger createLogger();
}
// 具体工厂
class FileLoggerFactory extends LoggerFactory {
@Override
public Logger createLogger() {
return new FileLogger();
}
}
class ConsoleLoggerFactory extends LoggerFactory {
@Override
public Logger createLogger() {
return new ConsoleLogger();
}
}
// 使用
LoggerFactory factory = new FileLoggerFactory();
Logger logger = factory.createLogger();
logger.log("系统启动"); // 输出:写入文件日志: 系统启动
抽象工厂模式 (Abstract Factory)
场景:不同品牌的电脑(华硕/联想)生产各自的CPU和内存
// 产品族:CPU
interface CPU {
void process();
}
class AsusCPU implements CPU {
@Override
public void process() {
System.out.println("华硕 CPU 处理中");
}
}
class LenovoCPU implements CPU {
@Override
public void process() {
System.out.println("联想 CPU 处理中");
}
}
// 产品族:内存
interface Memory {
void store();
}
class AsusMemory implements Memory {
@Override
public void store() {
System.out.println("华硕 内存存储");
}
}
class LenovoMemory implements Memory {
@Override
public void store() {
System.out.println("联想 内存存储");
}
}
// 抽象工厂
interface ComputerFactory {
CPU createCPU();
Memory createMemory();
}
// 具体工厂
class AsusFactory implements ComputerFactory {
@Override
public CPU createCPU() {
return new AsusCPU();
}
@Override
public Memory createMemory() {
return new AsusMemory();
}
}
class LenovoFactory implements ComputerFactory {
@Override
public CPU createCPU() {
return new LenovoCPU();
}
@Override
public Memory createMemory() {
return new LenovoMemory();
}
}
// 使用
ComputerFactory factory = new AsusFactory();
CPU cpu = factory.createCPU();
Memory memory = factory.createMemory();
cpu.process(); // 华硕 CPU 处理中
memory.store(); // 华硕 内存存储
建造者模式 (Builder)
场景:创建复杂的对象(如用户信息,有多个可选参数)
public class User {
// 必选参数
private final String username;
private final String password;
// 可选参数
private final int age;
private final String email;
private final String phone;
private User(Builder builder) {
this.username = builder.username;
this.password = builder.password;
this.age = builder.age;
this.email = builder.email;
this.phone = builder.phone;
}
public static class Builder {
private final String username;
private final String password;
private int age;
private String email;
private String phone;
public Builder(String username, String password) {
this.username = username;
this.password = password;
}
public Builder age(int age) {
this.age = age;
return this;
}
public Builder email(String email) {
this.email = email;
return this;
}
public Builder phone(String phone) {
this.phone = phone;
return this;
}
public User build() {
return new User(this);
}
}
@Override
public String toString() {
return "User{username='" + username + "', age=" + age + ", email='" + email + "'}";
}
}
// 使用 - 链式调用
User user = new User.Builder("zhangsan", "123456")
.age(25)
.email("zhangsan@mail.com")
.build();
System.out.println(user); // User{username='zhangsan', age=25, email='zhangsan@mail.com'}
原型模式 (Prototype)
场景:复制复杂对象,避免重复初始化开销
import java.util.ArrayList;
import java.util.List;
class Document implements Cloneable {
private String title;
private List<String> content;
public Document(String title) {
this.title = title;
this.content = new ArrayList<>();
}
public void addContent(String line) {
content.add(line);
}
// 深拷贝
@Override
public Document clone() {
try {
Document cloned = (Document) super.clone();
// 深拷贝内容列表
cloned.content = new ArrayList<>(this.content);
return cloned;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
@Override
public String toString() {
return "Document{title='" + title + "', content=" + content + "}";
}
}
// 使用
Document original = new Document("报告");
original.addContent("第一页内容");
original.addContent("第二页内容");
Document copy = original.clone(); // 快速复制
copy.addContent("新增的第三页内容");
System.out.println(original); // Document{title='报告', content=[第一页内容, 第二页内容]}
System.out.println(copy); // Document{title='报告', content=[第一页内容, 第二页内容, 新增的第三页内容]}
结构型模式(7种)
适配器模式 (Adapter)
场景:兼容旧系统接口,让不兼容的类一起工作
// 已有的旧接口(不兼容)
class OldPaymentSystem {
public void oldPay(String account, double amount) {
System.out.println("旧系统支付: " + account + " - " + amount);
}
}
// 新系统期待的接口
interface NewPaymentSystem {
void pay(String userId, double money);
}
// 适配器 - 将旧接口适配到新接口
class PaymentAdapter implements NewPaymentSystem {
private OldPaymentSystem oldSystem;
public PaymentAdapter(OldPaymentSystem oldSystem) {
this.oldSystem = oldSystem;
}
@Override
public void pay(String userId, double money) {
// 参数转换 + 调用旧方法
oldSystem.oldPay(userId, money);
}
}
// 使用
OldPaymentSystem oldSystem = new OldPaymentSystem();
NewPaymentSystem adapter = new PaymentAdapter(oldSystem);
adapter.pay("user123", 99.99); // 输出:旧系统支付: user123 - 99.99
代理模式 (Proxy)
场景:权限控制、延迟加载、日志记录
// 真实业务接口
interface Database {
void query(String sql);
}
// 真实对象
class RealDatabase implements Database {
@Override
public void query(String sql) {
System.out.println("执行SQL: " + sql);
}
}
// 代理对象 - 增加权限检查
class DatabaseProxy implements Database {
private RealDatabase realDatabase;
private String currentUser;
public DatabaseProxy(String currentUser) {
this.currentUser = currentUser;
this.realDatabase = new RealDatabase();
}
@Override
public void query(String sql) {
if (!"admin".equals(currentUser)) {
System.out.println("权限不足!只有admin可以执行查询");
return;
}
// 前置增强
System.out.println("[日志] " + currentUser + " 执行查询: " + sql);
realDatabase.query(sql);
// 后置增强
System.out.println("[日志] 查询执行完毕");
}
}
// 使用
Database db = new DatabaseProxy("guest");
db.query("SELECT * FROM users");
// 输出:权限不足!只有admin可以执行查询
db = new DatabaseProxy("admin");
db.query("SELECT * FROM users");
// 输出:
// [日志] admin 执行查询: SELECT * FROM users
// 执行SQL: SELECT * FROM users
// [日志] 查询执行完毕
装饰模式 (Decorator)
场景:动态给对象添加功能(如给咖啡加糖、加奶)
// 抽象组件
interface Coffee {
String getDescription();
double getCost();
}
// 具体组件
class SimpleCoffee implements Coffee {
@Override
public String getDescription() {
return "简单咖啡";
}
@Override
public double getCost() {
return 5.0;
}
}
// 抽象装饰器
abstract class CoffeeDecorator implements Coffee {
protected Coffee decoratedCoffee;
public CoffeeDecorator(Coffee coffee) {
this.decoratedCoffee = coffee;
}
}
// 具体装饰器 - 加牛奶
class MilkDecorator extends CoffeeDecorator {
public MilkDecorator(Coffee coffee) {
super(coffee);
}
@Override
public String getDescription() {
return decoratedCoffee.getDescription() + " + 牛奶";
}
@Override
public double getCost() {
return decoratedCoffee.getCost() + 2.0;
}
}
// 具体装饰器 - 加糖
class SugarDecorator extends CoffeeDecorator {
public SugarDecorator(Coffee coffee) {
super(coffee);
}
@Override
public String getDescription() {
return decoratedCoffee.getDescription() + " + 糖";
}
@Override
public double getCost() {
return decoratedCoffee.getCost() + 1.0;
}
}
// 使用 - 层层装饰
Coffee coffee = new SimpleCoffee();
coffee = new MilkDecorator(coffee);
coffee = new SugarDecorator(coffee);
System.out.println(coffee.getDescription()); // 简单咖啡 + 牛奶 + 糖
System.out.println("总价: " + coffee.getCost()); // 总价: 8.0
外观模式 (Facade)
场景:为复杂的子系统提供统一入口
// 三个复杂子系统
class CPU {
public void start() { System.out.println("CPU 启动"); }
public void stop() { System.out.println("CPU 关闭"); }
}
class Memory {
public void load() { System.out.println("内存加载数据"); }
public void unload() { System.out.println("内存释放数据"); }
}
class HardDrive {
public void read() { System.out.println("硬盘读取"); }
public void write() { System.out.println("硬盘写入"); }
}
// 外观类 - 提供简单接口
class ComputerFacade {
private CPU cpu;
private Memory memory;
private HardDrive hardDrive;
public ComputerFacade() {
this.cpu = new CPU();
this.memory = new Memory();
this.hardDrive = new HardDrive();
}
// 一键启动
public void start() {
System.out.println("=== 计算机启动 ===");
cpu.start();
memory.load();
hardDrive.read();
System.out.println("=== 启动完成 ===");
}
// 一键关机
public void shutdown() {
System.out.println("=== 计算机关闭 ===");
hardDrive.write();
memory.unload();
cpu.stop();
System.out.println("=== 关闭完成 ===");
}
}
// 使用 - 客户端只需调两个方法
ComputerFacade computer = new ComputerFacade();
computer.start();
computer.shutdown();
桥接模式 (Bridge)
场景:一个类有两个独立变化的维度(如:不同形状 + 不同颜色)
// 颜色接口(实现部分)
interface Color {
void applyColor();
}
class Red implements Color {
@Override
public void applyColor() {
System.out.print("红色");
}
}
class Blue implements Color {
@Override
public void applyColor() {
System.out.print("蓝色");
}
}
// 形状抽象类(抽象部分)
abstract class Shape {
protected Color color;
public Shape(Color color) {
this.color = color;
}
public abstract void draw();
}
// 具体形状
class Circle extends Shape {
public Circle(Color color) {
super(color);
}
@Override
public void draw() {
System.out.print("画一个");
color.applyColor();
System.out.println("的圆形");
}
}
class Square extends Shape {
public Square(Color color) {
super(color);
}
@Override
public void draw() {
System.out.print("画一个");
color.applyColor();
System.out.println("的正方形");
}
}
// 使用 - 形状和颜色可以任意组合
Shape shape1 = new Circle(new Red());
shape1.draw(); // 画一个红色的圆形
Shape shape2 = new Square(new Blue());
shape2.draw(); // 画一个蓝色的正方形
Shape shape3 = new Circle(new Blue());
shape3.draw(); // 画一个蓝色的圆形
组合模式 (Composite)
场景:树形结构(文件夹、组织架构)
import java.util.ArrayList;
import java.util.List;
// 抽象组件
interface FileSystemNode {
void display(String indent);
}
// 叶子节点 - 文件
class FileLeaf implements FileSystemNode {
private String name;
public FileLeaf(String name) {
this.name = name;
}
@Override
public void display(String indent) {
System.out.println(indent + "📄 " + name);
}
}
// 容器节点 - 文件夹
class FolderComposite implements FileSystemNode {
private String name;
private List<FileSystemNode> children = new ArrayList<>();
public FolderComposite(String name) {
this.name = name;
}
public void add(FileSystemNode node) {
children.add(node);
}
public void remove(FileSystemNode node) {
children.remove(node);
}
@Override
public void display(String indent) {
System.out.println(indent + "📁 " + name);
for (FileSystemNode child : children) {
child.display(indent + " ");
}
}
}
// 使用 - 构建文件树
FolderComposite root = new FolderComposite("根目录");
FolderComposite docs = new FolderComposite("文档");
FolderComposite images = new FolderComposite("图片");
docs.add(new FileLeaf("报告.doc"));
docs.add(new FileLeaf("说明.txt"));
images.add(new FileLeaf("风景.jpg"));
images.add(new FileLeaf("头像.png"));
root.add(docs);
root.add(images);
root.add(new FileLeaf("README.md"));
root.display("");
// 输出:
// 📁 根目录
// 📁 文档
// 📄 报告.doc
// 📄 说明.txt
// 📁 图片
// 📄 风景.jpg
// 📄 头像.png
// 📄 README.md
享元模式 (Flyweight)
场景:大量相似对象共享数据(如:文本编辑器中的字符样式)
import java.util.HashMap;
import java.util.Map;
// 享元对象 - 字符样式
class CharacterStyle {
private final String font;
private final int size;
private final String color;
public CharacterStyle(String font, int size, String color) {
this.font = font;
this.size = size;
this.color = color;
}
public void display(char character) {
System.out.println("字符: " + character + " [字体=" + font + ", 大小=" + size + ", 颜色=" + color + "]");
}
}
// 享元工厂 - 缓存样式对象
class StyleFactory {
private static Map<String, CharacterStyle> styleCache = new HashMap<>();
public static CharacterStyle getStyle(String font, int size, String color) {
String key = font + "|" + size + "|" + color;
if (!styleCache.containsKey(key)) {
styleCache.put(key, new CharacterStyle(font, size, color));
System.out.println("创建新样式: " + key);
}
return styleCache.get(key);
}
}
// 使用
class TextEditor {
public void renderText(String text, String font, int size, String color) {
CharacterStyle style = StyleFactory.getStyle(font, size, color);
for (char c : text.toCharArray()) {
style.display(c);
}
}
}
// 使用
TextEditor editor = new TextEditor();
editor.renderText("Hello", "Arial", 12, "black");
// 创建新样式: Arial|12|black
// 字符: H [字体=Arial, 大小=12, 颜色=black]
// ...
editor.renderText("World", "Arial", 12, "black");
// 使用缓存,不再创建新对象
// 字符: W [字体=Arial, 大小=12, 颜色=black]
// ...
行为型模式(11种)
策略模式 (Strategy)
场景:不同的支付方式、不同的折扣计算
// 策略接口
interface PaymentStrategy {
void pay(double amount);
}
// 具体策略 - 信用卡支付
class CreditCardPayment implements PaymentStrategy {
private String cardNumber;
public CreditCardPayment(String cardNumber) {
this.cardNumber = cardNumber;
}
@Override
public void pay(double amount) {
System.out.println("使用信用卡 " + cardNumber + " 支付 " + amount + " 元");
}
}
// 具体策略 - 支付宝支付
class AlipayPayment implements PaymentStrategy {
private String account;
public AlipayPayment(String account) {
this.account = account;
}
@Override
public void pay(double amount) {
System.out.println("使用支付宝账户 " + account + " 支付 " + amount + " 元");
}
}
// 上下文 - 使用策略
class Order {
private PaymentStrategy paymentStrategy;
public void setPaymentStrategy(PaymentStrategy strategy) {
this.paymentStrategy = strategy;
}
public void checkout(double amount) {
System.out.println("订单总金额: " + amount);
paymentStrategy.pay(amount);
}
}
// 使用
Order order = new Order();
order.setPaymentStrategy(new CreditCardPayment("1234-5678"));
order.checkout(299.99);
// 输出:
// 订单总金额: 299.99
// 使用信用卡 1234-5678 支付 299.99 元
order.setPaymentStrategy(new AlipayPayment("zhangsan@mail.com"));
order.checkout(599.99);
// 输出:
// 订单总金额: 599.99
// 使用支付宝账户 zhangsan@mail.com 支付 599.99 元
观察者模式 (Observer)
场景:消息推送、股票价格更新、事件监听
import java.util.ArrayList;
import java.util.List;
// 观察者接口
interface Observer {
void update(String news);
}
// 主题(被观察者)
class NewsAgency {
private List<Observer> observers = new ArrayList<>();
private String latestNews;
public void addObserver(Observer observer) {
observers.add(observer);
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
public void setNews(String news) {
this.latestNews = news;
notifyAllObservers();
}
private void notifyAllObservers() {
for (Observer observer : observers) {
observer.update(latestNews);
}
}
}
// 具体观察者 - 手机用户
class MobileUser implements Observer {
private String name;
public MobileUser(String name) {
this.name = name;
}
@Override
public void update(String news) {
System.out.println(name + " 的手机收到推送: " + news);
}
}
// 具体观察者 - 邮件订阅者
class EmailSubscriber implements Observer {
private String email;
public EmailSubscriber(String email) {
this.email = email;
}
@Override
public void update(String news) {
System.out.println("发送邮件到 " + email + ": " + news);
}
}
// 使用
NewsAgency agency = new NewsAgency();
agency.addObserver(new MobileUser("张三"));
agency.addObserver(new MobileUser("李四"));
agency.addObserver(new EmailSubscriber("admin@news.com"));
agency.setNews("Java 21 正式发布!");
// 输出:
// 张三 的手机收到推送: Java 21 正式发布!
// 李四 的手机收到推送: Java 21 正式发布!
// 发送邮件到 admin@news.com: Java 21 正式发布!
责任链模式 (Chain of Responsibility)
场景:审批流程、日志处理、过滤器链
// 请求对象
class LeaveRequest {
private String employee;
private int days;
public LeaveRequest(String employee, int days) {
this.employee = employee;
this.days = days;
}
public String getEmployee() { return employee; }
public int getDays() { return days; }
}
// 抽象处理者
abstract class Approver {
protected Approver nextApprover;
public void setNext(Approver next) {
this.nextApprover = next;
}
public abstract void handleRequest(LeaveRequest request);
}
// 具体处理者 - 主管(可批2天以内)
class Supervisor extends Approver {
@Override
public void handleRequest(LeaveRequest request) {
if (request.getDays() <= 2) {
System.out.println("主管批准 " + request.getEmployee() + " 的 " + request.getDays() + " 天请假");
} else if (nextApprover != null) {
System.out.println("主管无权审批,转交上级");
nextApprover.handleRequest(request);
}
}
}
// 具体处理者 - 经理(可批7天以内)
class Manager extends Approver {
@Override
public void handleRequest(LeaveRequest request) {
if (request.getDays() <= 7) {
System.out.println("经理批准 " + request.getEmployee() + " 的 " + request.getDays() + " 天请假");
} else if (nextApprover != null) {
System.out.println("经理无权审批,转交上级");
nextApprover.handleRequest(request);
}
}
}
// 具体处理者 - 总监(可批30天以内)
class Director extends Approver {
@Override
public void handleRequest(LeaveRequest request) {
if (request.getDays() <= 30) {
System.out.println("总监批准 " + request.getEmployee() + " 的 " + request.getDays() + " 天请假");
} else {
System.out.println("请假天数过多,总监拒绝");
}
}
}
// 使用 - 构建责任链
Approver supervisor = new Supervisor();
Approver manager = new Manager();
Approver director = new Director();
supervisor.setNext(manager);
manager.setNext(director);
// 发起请求
LeaveRequest request1 = new LeaveRequest("张三", 1);
supervisor.handleRequest(request1);
// 输出:主管批准 张三 的 1 天请假
LeaveRequest request2 = new LeaveRequest("李四", 5);
supervisor.handleRequest(request2);
// 输出:
// 主管无权审批,转交上级
// 经理批准 李四 的 5 天请假
LeaveRequest request3 = new LeaveRequest("王五", 20);
supervisor.handleRequest(request3);
// 输出:
// 主管无权审批,转交上级
// 经理无权审批,转交上级
// 总监批准 王五 的 20 天请假
模板方法模式 (Template Method)
场景:数据库查询模板、游戏流程、数据导出
// 抽象类 - 定义算法骨架
abstract class DataExporter {
// 模板方法 - 定义流程
public final void export() {
System.out.println("=== 开始导出 ===");
connect();
loadData();
formatData();
writeFile();
disconnect();
System.out.println("=== 导出完成 ===");
}
// 具体实现(共同部分)
private void connect() {
System.out.println("连接数据库...");
}
private void disconnect() {
System.out.println("断开数据库连接...");
}
// 抽象方法(差异化部分,由子类实现)
protected abstract void loadData();
protected abstract void formatData();
protected abstract void writeFile();
}
// 具体子类 - 导出为Excel
class ExcelExporter extends DataExporter {
@Override
protected void loadData() {
System.out.println("从数据库加载数据 (用户表)");
}
@Override
protected void formatData() {
System.out.println("格式化为 Excel 格式 (.xlsx)");
}
@Override
protected void writeFile() {
System.out.println("写入文件: report.xlsx");
}
}
// 具体子类 - 导出为PDF
class PdfExporter extends DataExporter {
@Override
protected void loadData() {
System.out.println("从数据库加载数据 (订单表)");
}
@Override
protected void formatData() {
System.out.println("格式化为 PDF 格式");
}
@Override
protected void writeFile() {
System.out.println("写入文件: invoice.pdf");
}
}
// 使用
DataExporter exporter = new ExcelExporter();
exporter.export();
// 输出完整的导出流程
exporter = new PdfExporter();
exporter.export();
命令模式 (Command)
场景:操作撤销/重做、任务队列、遥控器按钮
// 命令接口
interface Command {
void execute();
void undo();
}
// 接收者 - 电视机
class Television {
private int volume = 10;
public void turnOn() {
System.out.println("电视已开启");
}
public void turnOff() {
System.out.println("电视已关闭");
}
public void volumeUp() {
System.out.println("音量增大: " + (++volume));
}
public void volumeDown() {
System.out.println("音量减小: " + (--volume));
}
}
// 具体命令 - 开机
class TurnOnCommand implements Command {
private Television tv;
public TurnOnCommand(Television tv) {
this.tv = tv;
}
@Override
public void execute() {
tv.turnOn();
}
@Override
public void undo() {
tv.turnOff();
}
}
// 具体命令 - 关机
class TurnOffCommand implements Command {
private Television tv;
public TurnOffCommand(Television tv) {
this.tv = tv;
}
@Override
public void execute() {
tv.turnOff();
}
@Override
public void undo() {
tv.turnOn();
}
}
// 具体命令 - 音量加
class VolumeUpCommand implements Command {
private Television tv;
public VolumeUpCommand(Television tv) {
this.tv = tv;
}
@Override
public void execute() {
tv.volumeUp();
}
@Override
public void undo() {
tv.volumeDown();
}
}
// 调用者 - 遥控器
class RemoteControl {
private Command[] commands = new Command[2];
private Command lastCommand;
public void setCommand(int slot, Command command) {
commands[slot] = command;
}
public void pressButton(int slot) {
if (commands[slot] != null) {
commands[slot].execute();
lastCommand = commands[slot];
}
}
public void pressUndo() {
if (lastCommand != null) {
System.out.println(">>> 撤销上一步操作");
lastCommand.undo();
}
}
}
// 使用
Television tv = new Television();
RemoteControl remote = new RemoteControl();
remote.setCommand(0, new TurnOnCommand(tv));
remote.setCommand(1, new VolumeUpCommand(tv));
remote.pressButton(0); // 电视已开启
remote.pressButton(1); // 音量增大: 11
remote.pressButton(1); // 音量增大: 12
remote.pressUndo(); // >>> 撤销上一步操作 / 音量减小: 11
迭代器模式 (Iterator)
场景:遍历集合的不同方式
import java.util.Iterator;
// 自定义集合
class BookCollection implements Iterable<String> {
private String[] books;
private int size;
public BookCollection(int capacity) {
books = new String[capacity];
size = 0;
}
public void addBook(String book) {
if (size < books.length) {
books[size++] = book;
}
}
@Override
public Iterator<String> iterator() {
return new BookIterator();
}
// 自定义迭代器
private class BookIterator implements Iterator<String> {
private int index = 0;
@Override
public boolean hasNext() {
return index < size;
}
@Override
public String next() {
return books[index++];
}
}
}
// 使用
BookCollection library = new BookCollection(5);
library.addBook("Java 编程思想");
library.addBook("设计模式");
library.addBook("Spring 实战");
for (String book : library) {
System.out.println("书籍: " + book);
}
// 输出:
// 书籍: Java 编程思想
// 书籍: 设计模式
// 书籍: Spring 实战
状态模式 (State)
场景:订单状态切换、电梯状态
// 上下文 - 订单
class Order {
private OrderState state;
public Order() {
this.state = new PendingState(); // 初始状态:待支付
}
void setState(OrderState state) {
this.state = state;
}
void pay() {
state.pay(this);
}
void ship() {
state.ship(this);
}
void complete() {
state.complete(this);
}
}
// 状态接口
interface OrderState {
void pay(Order order);
void ship(Order order);
void complete(Order order);
}
// 具体状态 - 待支付
class PendingState implements OrderState {
@Override
public void pay(Order order) {
System.out.println("支付成功,订单已确认");
order.setState(new ConfirmedState());
}
@Override
public void ship(Order order) {
System.out.println("未支付,无法发货");
}
@Override
public void complete(Order order) {
System.out.println("未支付,无法完成");
}
}
// 具体状态 - 已确认
class ConfirmedState implements OrderState {
@Override
public void pay(Order order) {
System.out.println("订单已支付,无需重复支付");
}
@Override
public void ship(Order order) {
System.out.println("订单已发货");
order.setState(new ShippedState());
}
@Override
public void complete(Order order) {
System.out.println("订单未发货,无法完成");
}
}
// 具体状态 - 已发货
class ShippedState implements OrderState {
@Override
public void pay(Order order) {
System.out.println("订单已发货,无需支付");
}
@Override
public void ship(Order order) {
System.out.println("已发货,无需重复发货");
}
@Override
public void complete(Order order) {
System.out.println("订单已完成");
order.setState(new CompletedState());
}
}
// 具体状态 - 已完成
class CompletedState implements OrderState {
@Override
public void pay(Order order) {
System.out.println("订单已完成,无需支付");
}
@Override
public void ship(Order order) {
System.out.println("订单已完成,无需发货");
}
@Override
public void complete(Order order) {
System.out.println("订单已完成,无需重复完成");
}
}
// 使用
Order order = new Order();
order.pay(); // 支付成功,订单已确认
order.ship(); // 订单已发货
order.complete(); // 订单已完成
order.pay(); // 订单已完成,无需支付
备忘录模式 (Memento)
场景:游戏存档、撤销操作
// 备忘录 - 保存状态
class Memento {
private String content;
private int version;
public Memento(String content, int version) {
this.content = content;
this.version = version;
}
public String getContent() { return content; }
public int getVersion() { return version; }
}
// 发起人 - 编辑器
class Editor {
private String content = "";
private int version = 0;
public void type(String text) {
content += text;
version++;
}
public String getContent() {
return content;
}
// 保存状态
public Memento save() {
return new Memento(content, version);
}
// 恢复状态
public void restore(Memento memento) {
this.content = memento.getContent();
this.version = memento.getVersion();
System.out.println("恢复到版本 " + version + ": " + content);
}
}
// 管理者 - 历史记录
class HistoryManager {
private Stack<Memento> history = new Stack<>();
public void push(Memento memento) {
history.push(memento);
}
public Memento pop() {
if (!history.isEmpty()) {
return history.pop();
}
return null;
}
}
// 使用
Editor editor = new Editor();
HistoryManager history = new HistoryManager();
editor.type("Hello ");
history.push(editor.save());
editor.type("World ");
history.push(editor.save());
editor.type("!");
System.out.println("当前内容: " + editor.getContent()); // Hello World !
// 撤销 - 恢复到上一个版本
editor.restore(history.pop()); // 恢复到版本 2: Hello World
editor.restore(history.pop()); // 恢复到版本 1: Hello
访问者模式 (Visitor)
场景:对对象结构进行不同的操作(如:商品定价 + 打折)
import java.util.ArrayList;
import java.util.List;
// 元素接口
interface Element {
void accept(Visitor visitor);
}
// 具体元素 - 书籍
class Book implements Element {
private String title;
private double price;
public Book(String title, double price) {
this.title = title;
this.price = price;
}
public String getTitle() { return title; }
public double getPrice() { return price; }
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
// 具体元素 - 电子产品
class Electronics implements Element {
private String name