java23种设计模式示例-元一软件

张开发
2026/4/16 15:39:26 15 分钟阅读

分享文章

java23种设计模式示例-元一软件
创建型模式关注对象的创建过程使系统独立于其对象的创建、组合和表示1. 单例模式-饿汉式单Singleton确保一个类只有一个实例并提供一个全局访问点。常用于数据库连接池、配置管理等场景。类加载时就初始化天生线程安全适合小对象。// 饿汉式单例 public class Singleton1 { // 1. 私有静态常量类加载时就创建实例 private static final Singleton1 INSTANCE new Singleton1(); // 2. 私有构造方法禁止外部 new 对象 private Singleton1() {} // 3. 公共静态方法获取唯一实例 public static Singleton1 getInstance() { return INSTANCE; } }2. 单例模式-双重校验锁DCL推荐线程安全 高性能企业开发最常用兼顾懒加载 线程安全 高性能。// 双重校验锁 DCL 单例推荐 public class Singleton2 { // volatile 禁止指令重排保证线程安全 private static volatile Singleton2 instance; private Singleton2() {} public static Singleton2 getInstance() { // 第一次检查不加锁提高性能 if (instance null) { // 加锁 synchronized (Singleton2.class) { // 第二次检查防止多线程同时进入 if (instance null) { instance new Singleton2(); } } } return instance; } }2. 工厂方法模式Factory Method定义创建对象的接口让子类决定实例化哪个类。// 工厂方法模式示例[reference:6] interface Logger { void log(String message); } class FileLogger implements Logger { public void log(String message) { System.out.println(记录日志到文件 message); } } interface LoggerFactory { Logger createLogger(); } class FileLoggerFactory implements LoggerFactory { public Logger createLogger() { return new FileLogger(); } }3. 抽象工厂模式Abstract Factory创建一系列相关或相互依赖的对象家族而无需指定它们的具体类。// 抽象工厂模式示例[reference:8] interface SmartDevice { void boot(); } class ApplePhone implements SmartDevice { public void boot() {} } class SamsungPhone implements SmartDevice { public void boot() {} } interface DeviceFactory { SmartDevice createPhone(); SmartDevice createWatch(); } class AppleFactory implements DeviceFactory { public SmartDevice createPhone() { return new ApplePhone(); } public SmartDevice createWatch() { return new AppleWatch(); } }4. 建造者模式Builder将复杂对象的构建与表示分离使同样的构建过程可以创建不同的表示。// 建造者模式示例[reference:10] public class Computer { private String cpu, ram; private Computer(Builder builder) { this.cpu builder.cpu; this.ram builder.ram; } public static class Builder { private String cpu, ram; public Builder cpu(String cpu) { this.cpu cpu; return this; } public Builder ram(String ram) { this.ram ram; return this; } public Computer build() { return new Computer(this); } } } // 使用: Computer c new Computer.Builder().cpu(i7).ram(16G).build();5. 原型模式Prototype通过复制现有对象来创建新对象避免重新初始化的开销。// 原型模式示例——实现Cloneable接口[reference:12] abstract class Shape implements Cloneable { public Shape clone() throws CloneNotSupportedException { return (Shape) super.clone(); } } class Circle extends Shape { private int radius; public Circle(int r) { this.radius r; } public void draw() { System.out.println(绘制圆形半径 radius); } }结构型模式关注类和对象的组合用于构建更大的结构。6. 适配器模式Adapter将一个接口转换成客户端期望的另一个接口使不兼容的接口能够协作。// 类适配器示例——使用继承实现 interface Target { void request(); } class Adaptee { void specificRequest() { System.out.println(被适配的方法); } } class Adapter extends Adaptee implements Target { public void request() { specificRequest(); } }7. 桥接模式Bridge将抽象部分与实现部分分离使它们可以独立变化。常用于 JDBC 驱动设计。// 桥接模式示例——电器与开关的解耦 interface Switch { void operate(); } class Light { void on() {} void off() {} } class LightSwitch implements Switch { private Light light; public LightSwitch(Light light) { this.light light; } public void operate() { light.on(); } }8. 组合模式Composite将对象组合成树形结构以表示部分-整体的层次结构。// 组合模式示例——文件系统的树形结构[reference:18] interface FileSystemComponent { void display(); } class File implements FileSystemComponent { private String name; public File(String name) { this.name name; } public void display() { System.out.println(文件 name); } } class Directory implements FileSystemComponent { private ListFileSystemComponent children new ArrayList(); public void add(FileSystemComponent c) { children.add(c); } public void display() { children.forEach(FileSystemComponent::display); } }9. 装饰器模式Decorator动态地给对象添加额外的职责提供比继承更灵活的扩展方式。// 装饰器模式示例——为披萨添加配料[reference:20] interface Pizza { String getDescription(); double cost(); } class PlainPizza implements Pizza { public String getDescription() { return 基础披萨; } public double cost() { return 50.0; } } abstract class ToppingDecorator implements Pizza { protected Pizza pizza; public ToppingDecorator(Pizza pizza) { this.pizza pizza; } } class Cheese extends ToppingDecorator { public Cheese(Pizza pizza) { super(pizza); } public String getDescription() { return pizza.getDescription() 加芝士; } public double cost() { return pizza.cost() 8.0; } }10. 外观模式Facade为子系统中的一组接口提供一个统一的高层接口简化客户端使用。// 外观模式示例——电脑启动的简化[reference:22] class CPU { void start() {} } class Memory { void load() {} } class HardDrive { void read() {} } class ComputerFacade { private CPU cpu new CPU(); private Memory memory new Memory(); private HardDrive hardDrive new HardDrive(); public void start() { cpu.start(); memory.load(); hardDrive.read(); System.out.println(电脑已启动); } }11. 享元模式Flyweight通过共享技术有效支持大量细粒度对象的重用减少内存占用。java// 享元模式示例——图形共享[reference:24] class ShapeFactory { private static final MapString, Shape shapes new HashMap(); public static Shape getShape(String color) { Shape shape shapes.get(color); if (shape null) { shape new Circle(color); shapes.put(color, shape); } return shape; } }12. 代理模式Proxy为其他对象提供一种代理以控制对该对象的访问。java// 动态代理示例[reference:26] interface Service { void doSomething(); } class ServiceImpl implements Service { public void doSomething() { System.out.println(执行业务逻辑); } } class LogProxy implements InvocationHandler { private Object target; public LogProxy(Object target) { this.target target; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println(日志开始执行 method.getName()); return method.invoke(target, args); } }行为型模式关注对象之间的责任分配和算法封装。13. 责任链模式Chain of Responsibility将请求的发送者和接收者解耦使多个对象都有机会处理请求。java// 责任链模式示例——审批流程[reference:29] abstract class Handler { protected Handler next; public void setNext(Handler next) { this.next next; } public abstract void handleRequest(int days); } class Manager extends Handler { public void handleRequest(int days) { if (days 3) System.out.println(经理批准请假); else if (next ! null) next.handleRequest(days); } }14. 命令模式Command将请求封装为对象支持请求的排队、记录日志和撤销操作。java// 命令模式示例——遥控器控制家电 interface Command { void execute(); } class LightOnCommand implements Command { private Light light; public LightOnCommand(Light light) { this.light light; } public void execute() { light.on(); } } class RemoteControl { private Command command; public void setCommand(Command c) { this.command c; } public void pressButton() { command.execute(); } }15. 解释器模式Interpreter定义语言的文法表示并提供一个解释器来解释语言中的句子。java// 解释器模式示例——简单算术表达式[reference:32] interface Expression { int interpret(); } class NumberExpression implements Expression { private int number; public NumberExpression(int n) { this.number n; } public int interpret() { return number; } } class AddExpression implements Expression { private Expression left, right; public AddExpression(Expression l, Expression r) { left l; right r; } public int interpret() { return left.interpret() right.interpret(); } }16. 迭代器模式Iterator提供一种顺序访问聚合对象元素的方法而不暴露其内部表示。java// 迭代器模式示例——自定义集合遍历[reference:34] interface IteratorT { boolean hasNext(); T next(); } class NameRepository implements IterableString { private String[] names {Alice, Bob, Charlie}; public IteratorString iterator() { return new IteratorString() { int index; public boolean hasNext() { return index names.length; } public String next() { return names[index]; } }; } }17. 中介者模式Mediator用一个中介对象封装一系列对象的交互使各对象松散耦合。java// 中介者模式示例——聊天室[reference:36] interface ChatMediator { void sendMessage(String msg, User user); } class ChatRoom implements ChatMediator { private ListUser users new ArrayList(); public void addUser(User u) { users.add(u); } public void sendMessage(String msg, User sender) { users.stream().filter(u - u ! sender) .forEach(u - u.receive(msg)); } } abstract class User { protected ChatMediator mediator; public User(ChatMediator m) { this.mediator m; } public abstract void send(String msg); public abstract void receive(String msg); }18. 备忘录模式Memento在不破坏封装的前提下捕获对象的内部状态并保存以便后续恢复。java// 备忘录模式示例——文本编辑器撤销功能[reference:38] class Editor { private String content; public EditorState save() { return new EditorState(content); } public void restore(EditorState state) { content state.getContent(); } public void setContent(String c) { content c; } static class EditorState { private final String content; EditorState(String c) { content c; } String getContent() { return content; } } }19. 观察者模式Observer定义对象间的一对多依赖关系当一个对象状态改变时所有依赖者都会收到通知。java// 观察者模式示例——天气站通知显示器[reference:40] interface Observer { void update(float temperature); } class WeatherStation { private ListObserver observers new ArrayList(); private float temperature; public void addObserver(Observer o) { observers.add(o); } public void notifyObservers() { observers.forEach(o - o.update(temperature)); } public void setTemperature(float t) { this.temperature t; notifyObservers(); } }20. 状态模式State允许对象在内部状态改变时改变其行为对象看起来像是修改了它的类。java// 状态模式示例——电梯状态转换[reference:42] interface ElevatorState { void handle(); } class StoppedState implements ElevatorState { public void handle() { System.out.println(电梯停止); } } class MovingState implements ElevatorState { public void handle() { System.out.println(电梯运行中); } } class Elevator { private ElevatorState state new StoppedState(); public void setState(ElevatorState s) { this.state s; } public void operate() { state.handle(); } }21. 策略模式Strategy定义一系列算法并封装使它们可以相互替换算法变化不影响客户端。java// 策略模式示例——支付方式选择[reference:44] interface PaymentStrategy { void pay(int amount); } class CreditCardPayment implements PaymentStrategy { public void pay(int amount) { System.out.println(使用信用卡支付 amount 元); } } class ShoppingCart { private PaymentStrategy strategy; public void setStrategy(PaymentStrategy s) { strategy s; } public void checkout(int amount) { strategy.pay(amount); } }22. 模板方法模式Template Method在父类中定义算法骨架将某些步骤延迟到子类实现。java// 模板方法模式示例——饮料制作流程 abstract class Beverage { // 模板方法 public final void prepare() { boilWater(); brew(); pourInCup(); addCondiments(); } void boilWater() { System.out.println(烧开水); } abstract void brew(); void pourInCup() { System.out.println(倒入杯中); } abstract void addCondiments(); } class Tea extends Beverage { void brew() { System.out.println(冲泡茶叶); } void addCondiments() { System.out.println(加入柠檬); } }23. 访问者模式Visitor在不修改已有类层次结构的前提下为它们增加新的操作。java// 访问者模式示例——表达式计算[reference:47] interface Expression { void accept(Visitor v); } class Number implements Expression { private int value; public Number(int v) { value v; } public void accept(Visitor v) { v.visit(this); } public int getValue() { return value; } } interface Visitor { void visit(Number n); void visit(Add a); } class Calculator implements Visitor { private int result; public void visit(Number n) { result n.getValue(); } public void visit(Add a) { a.getLeft().accept(this); int left result; a.getRight().accept(this); result left; } }

更多文章