深入探讨Java设计模式:构建灵活而可维护的代码

深入探讨Java设计模式:构建灵活而可维护的代码

设计模式是在软件设计中,经过反复验证,以解决特定问题的最佳实践的经验总结。在Java中,设计模式是一种强大的工具,用于构建可扩展、灵活且易于维护的代码。本文将深入讨论一些常见的Java设计模式,以及它们在实际应用中的应用场景。

1. 单例模式(Singleton Pattern)

单例模式确保一个类只有一个实例,并提供一个全局访问点。这在需要共享资源的情况下非常有用,比如数据库连接、配置管理等。

public class Singleton {private static Singleton instance;private Singleton() {}public static Singleton getInstance() {if (instance == null) {instance = new Singleton();}return instance;}
}

2. 工厂模式(Factory Pattern)

工厂模式用于创建对象,通过定义一个接口或抽象类,然后由子类决定实例化哪一个类。这有助于封装对象的创建逻辑,提高代码的可维护性。

public interface Shape {void draw();
}public class Circle implements Shape {@Overridepublic void draw() {System.out.println("Draw a circle");}
}public class Square implements Shape {@Overridepublic void draw() {System.out.println("Draw a square");}
}public class ShapeFactory {public Shape getShape(String shapeType) {if (shapeType == null) {return null;}if (shapeType.equalsIgnoreCase("CIRCLE")) {return new Circle();} else if (shapeType.equalsIgnoreCase("SQUARE")) {return new Square();}return null;}
}

3. 观察者模式(Observer Pattern)

观察者模式定义了一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖它的对象都得到通知并自动更新。

import java.util.ArrayList;
import java.util.List;// 主题接口
public interface Subject {void addObserver(Observer observer);void removeObserver(Observer observer);void notifyObservers();
}// 具体主题
public class ConcreteSubject implements Subject {private List<Observer> observers = new ArrayList<>();@Overridepublic void addObserver(Observer observer) {observers.add(observer);}@Overridepublic void removeObserver(Observer observer) {observers.remove(observer);}@Overridepublic void notifyObservers() {for (Observer observer : observers) {observer.update();}}
}// 观察者接口
public interface Observer {void update();
}// 具体观察者
public class ConcreteObserver implements Observer {@Overridepublic void update() {System.out.println("Update received");}
}

4. 策略模式(Strategy Pattern)

策略模式定义了一族算法,将每个算法都封装起来,并且使它们之间可以互换。这使得算法可以独立于客户端而变化。

// 策略接口
public interface PaymentStrategy {void pay(int amount);
}// 具体策略
public class CreditCardPayment implements PaymentStrategy {@Overridepublic void pay(int amount) {System.out.println("Paid with credit card: " + amount);}
}public class PayPalPayment implements PaymentStrategy {@Overridepublic void pay(int amount) {System.out.println("Paid with PayPal: " + amount);}
}// 环境类
public class ShoppingCart {private PaymentStrategy paymentStrategy;public void setPaymentStrategy(PaymentStrategy paymentStrategy) {this.paymentStrategy = paymentStrategy;}public void checkout(int amount) {paymentStrategy.pay(amount);}
}

5. 模板方法模式(Template Method Pattern)

模板方法模式定义了一个算法的骨架,将一些步骤延迟到子类中实现。这样一来,子类可以在不改变算法结构的情况下重新定义算法的某些步骤。

// 抽象类
public abstract class Game {abstract void initialize();abstract void startPlay();abstract void endPlay();// 模板方法public final void play() {initialize();startPlay();endPlay();}
}// 具体类
public class Cricket extends Game {@Overridevoid initialize() {System.out.println("Cricket Game Initialized! Start playing.");}@Overridevoid startPlay() {System.out.println("Cricket Game Started. Enjoy the game!");}@Overridevoid endPlay() {System.out.println("Cricket Game Finished!");}
}public class Football extends Game {@Overridevoid initialize() {System.out.println("Football Game Initialized! Start playing.");}@Overridevoid startPlay() {System.out.println("Football Game Started. Enjoy the game!");}@Overridevoid endPlay() {System.out.println("Football Game Finished!");}
}

6. 装饰器模式(Decorator Pattern)

装饰器模式允许你通过将对象放入包装类中来给对象动态地添加新的功能。这种模式是继承关系的一个替代方案,它使得你可以灵活地扩展一个对象的功能。

// 抽象组件
public interface Shape {void draw();
}// 具体组件
public class Circle implements Shape {@Overridepublic void draw() {System.out.println("Draw a circle");}
}// 抽象装饰器
public abstract class ShapeDecorator implements Shape {protected Shape decoratedShape;public ShapeDecorator(Shape decoratedShape) {this.decoratedShape = decoratedShape;}public void draw() {decoratedShape.draw();}
}// 具体装饰器
public class RedShapeDecorator extends ShapeDecorator {public RedShapeDecorator(Shape decoratedShape) {super(decoratedShape);}@Overridepublic void draw() {decoratedShape.draw();setRedBorder(decoratedShape);}private void setRedBorder(Shape decoratedShape){System.out.println("Border Color: Red");}
}

7. 适配器模式(Adapter Pattern)

适配器模式允许接口不兼容的类能够协同工作。它通常用于让现有类与其他类一起工作,而无需修改其源代码。

// 目标接口
public interface Target {void request();
}// 具体目标
public class ConcreteTarget implements Target {@Overridepublic void request() {System.out.println("Target's request");}
}// 适配器
public class Adapter implements Target {private Adaptee adaptee;public Adapter(Adaptee adaptee) {this.adaptee = adaptee;}@Overridepublic void request() {adaptee.specificRequest();}
}// 源类
public class Adaptee {public void specificRequest() {System.out.println("Adaptee's specific request");}
}

8. 命令模式(Command Pattern)

命令模式将请求封装成对象,这可以让你参数化其他对象,队列化请求、以及支持可撤销的操作。

// 命令接口
public interface Command {void execute();
}// 具体命令
public class ConcreteCommand implements Command {private Receiver receiver;public ConcreteCommand(Receiver receiver) {this.receiver = receiver;}@Overridepublic void execute() {receiver.action();}
}// 接收者
public class Receiver {public void action() {System.out.println("Receiver's action");}
}// 调用者
public class Invoker {private Command command;public Invoker(Command command) {this.command = command;}public void invoke() {command.execute();}
}

9. 责任链模式(Chain of Responsibility Pattern)

责任链模式允许你将请求沿着处理者链进行传递,直到有一个处理者能够处理它。这种模式常用于系统中有多个对象可以处理同一请求的情况。

// 处理者接口
public interface Handler {void handleRequest(int request);void setNextHandler(Handler nextHandler);
}// 具体处理者
public class ConcreteHandler1 implements Handler {private Handler nextHandler;@Overridepublic void handleRequest(int request) {if (request < 10) {System.out.println("ConcreteHandler1 handles request: " + request);} else if (nextHandler != null) {nextHandler.handleRequest(request);}}@Overridepublic void setNextHandler(Handler nextHandler) {this.nextHandler = nextHandler;}
}public class ConcreteHandler2 implements Handler {private Handler nextHandler;@Overridepublic void handleRequest(int request) {if (request >= 10 && request < 20) {System.out.println("ConcreteHandler2 handles request: " + request);} else if (nextHandler != null) {nextHandler.handleRequest(request);}}@Overridepublic void setNextHandler(Handler nextHandler) {this.nextHandler = nextHandler;}
}

10. 迭代器模式(Iterator Pattern)

迭代器模式提供了一种顺序访问集合对象元素的方法,而不暴露集合的内部表示。通过使用迭代器模式,我们可以以一种统一的方式访问不同类型的集合。

// 迭代器接口
public interface Iterator {boolean hasNext();Object next();
}// 聚合接口
public interface Container {Iterator getIterator();
}// 具体迭代器
public class ConcreteIterator implements Iterator {private Object[] elements;private int position = 0;public ConcreteIterator(Object[] elements) {this.elements = elements;}@Overridepublic boolean hasNext() {return position < elements.length;}@Overridepublic Object next() {if (this.hasNext()) {return elements[position++];}return null;}
}// 具体聚合
public class ConcreteContainer implements Container {private Object[] elements;public ConcreteContainer(Object[] elements) {this.elements = elements;}@Overridepublic Iterator getIterator() {return new ConcreteIterator(elements);}
}

11. 代理模式(Proxy Pattern)

代理模式用于控制对对象的访问,充当被访问对象的中间层。它可以在不改变原始对象的情况下,增加额外的逻辑,比如延迟加载、权限控制等。

// 主题接口
public interface RealSubject {void request();
}// 具体主题
public class RealSubjectImpl implements RealSubject {@Overridepublic void request() {System.out.println("RealSubject handles request");}
}// 代理类
public class Proxy implements RealSubject {private RealSubjectImpl realSubject;@Overridepublic void request() {if (realSubject == null) {realSubject = new RealSubjectImpl();}// 可以在此处添加额外逻辑System.out.println("Proxy handles request");realSubject.request();}
}

12. 享元模式(Flyweight Pattern)

享元模式旨在减少对象的数量,以节省内存和提高性能。它通过共享相似对象之间的部分状态,以减小对象的存储开销。

// 享元接口
public interface Flyweight {void operation();
}// 具体享元
public class ConcreteFlyweight implements Flyweight {private String intrinsicState;public ConcreteFlyweight(String intrinsicState) {this.intrinsicState = intrinsicState;}@Overridepublic void operation() {System.out.println("ConcreteFlyweight with intrinsic state: " + intrinsicState);}
}// 享元工厂
public class FlyweightFactory {private Map<String, Flyweight> flyweights = new HashMap<>();public Flyweight getFlyweight(String key) {if (!flyweights.containsKey(key)) {flyweights.put(key, new ConcreteFlyweight(key));}return flyweights.get(key);}
}

13. 访问者模式(Visitor Pattern)

访问者模式将算法与对象结构分离,使得能够在不修改原始类的情况下添加新的操作。这对于处理复杂的对象结构,同时保持类的封装性非常有用。

// 元素接口
public interface Element {void accept(Visitor visitor);
}// 具体元素
public class ConcreteElement implements Element {@Overridepublic void accept(Visitor visitor) {visitor.visit(this);}
}// 访问者接口
public interface Visitor {void visit(ConcreteElement element);
}// 具体访问者
public class ConcreteVisitor implements Visitor {@Overridepublic void visit(ConcreteElement element) {System.out.println("Visitor visits ConcreteElement");}
}

14. 状态模式(State Pattern)

状态模式允许一个对象在其内部状态改变时改变它的行为。通过将状态抽象成独立的类,使得对象的状态可以独立于其行为而变化。

// 状态接口
public interface State {void handle(Context context);
}// 具体状态
public class ConcreteStateA implements State {@Overridepublic void handle(Context context) {System.out.println("Handling state A");context.setState(new ConcreteStateB());}
}public class ConcreteStateB implements State {@Overridepublic void handle(Context context) {System.out.println("Handling state B");context.setState(new ConcreteStateA());}
}// 上下文
public class Context {private State state;public Context(State state) {this.state = state;}public void setState(State state) {this.state = state;}public void request() {state.handle(this);}
}

15. 备忘录模式(Memento Pattern)

备忘录模式用于保存和恢复对象的状态,它允许在不暴露对象内部结构的情况下,捕获对象的状态快照。

// 备忘录
public class Memento {private String state;public Memento(String state) {this.state = state;}public String getState() {return state;}
}// 原发器
public class Originator {private String state;public void setState(String state) {this.state = state;}public String getState() {return state;}public Memento saveStateToMemento() {return new Memento(state);}public void getStateFromMemento(Memento memento) {state = memento.getState();}
}// 负责人
public class Caretaker {private List<Memento> mementos = new ArrayList<>();public void addMemento(Memento memento) {mementos.add(memento);}public Memento getMemento(int index) {return mementos.get(index);}
}

16. 桥接模式(Bridge Pattern)

桥接模式将抽象部分与它的实现部分分离,使它们可以独立变化。这种模式主要用于处理具有多维度变化的复杂系统,将系统抽象与实现解耦,使得系统更加灵活。

// 实现者接口
public interface Implementor {void operationImpl();
}// 具体实现者
public class ConcreteImplementorA implements Implementor {@Overridepublic void operationImpl() {System.out.println("Concrete Implementor A");}
}public class ConcreteImplementorB implements Implementor {@Overridepublic void operationImpl() {System.out.println("Concrete Implementor B");}
}// 抽象部分
public abstract class Abstraction {protected Implementor implementor;public Abstraction(Implementor implementor) {this.implementor = implementor;}public abstract void operation();
}// 具体抽象部分
public class RefinedAbstraction extends Abstraction {public RefinedAbstraction(Implementor implementor) {super(implementor);}@Overridepublic void operation() {System.out.print("Refined Abstraction - ");implementor.operationImpl();}
}

17. 组合模式(Composite Pattern)

组合模式允许客户以一致的方式处理单个对象和对象组合。它通过将对象组合成树形结构来表示部分-整体层次结构,从而使得客户可以统一地处理单个对象和组合对象。

// 组件接口
public interface Component {void operation();
}// 叶子节点
public class Leaf implements Component {@Overridepublic void operation() {System.out.println("Leaf operation");}
}// 容器节点
public class Composite implements Component {private List<Component> components = new ArrayList<>();public void add(Component component) {components.add(component);}public void remove(Component component) {components.remove(component);}@Overridepublic void operation() {System.out.println("Composite operation");for (Component component : components) {component.operation();}}
}

18. 命令查询职责隔离(CQRS)

CQRS是一种软件架构模式,它将命令和查询的职责分开。通过独立处理读取和写入操作,CQRS提供了更大的灵活性和性能优势。

// 命令处理器
public class CommandHandler {public void handleCommand(Command command) {// 处理命令}
}// 查询处理器
public class QueryHandler {public Result handleQuery(Query query) {// 处理查询return new Result();}
}// 命令
public class Command {// 命令的属性和方法
}// 查询
public class Query {// 查询的属性和方法
}// 查询结果
public class Result {// 结果的属性和方法
}

19. 观察者模式(Observer Pattern)在事件驱动中的应用

观察者模式在事件驱动系统中得到广泛应用。当一个事件发生时,所有注册的观察者都会被通知并执行相应的操作,从而实现了松耦合和更好的可维护性。

import java.util.ArrayList;
import java.util.List;// 主题
public class Subject {private List<Observer> observers = new ArrayList<>();public void addObserver(Observer observer) {observers.add(observer);}public void removeObserver(Observer observer) {observers.remove(observer);}public void notifyObservers() {for (Observer observer : observers) {observer.update();}}
}// 观察者
public interface Observer {void update();
}// 具体观察者
public class ConcreteObserver implements Observer {@Overridepublic void update() {System.out.println("ConcreteObserver updates");}
}

20. 亨元模式(Flyweight Pattern)在图形绘制中的应用

亨元模式用于共享细粒度的对象,以减小系统中对象的数量。在图形绘制中,亨元模式可以用于共享相同颜色、形状等属性的图形对象,提高系统的性能和资源利用率。

// 亨元接口
public interface Flyweight {void draw(int x, int y);
}// 具体亨元
public class ConcreteFlyweight implements Flyweight {private String color;public ConcreteFlyweight(String color) {this.color = color;}@Overridepublic void draw(int x, int y) {System.out.println("Drawing a " + color + " shape at (" + x + ", " + y + ")");}
}// 亨元工厂
public class FlyweightFactory {private Map<String, Flyweight> flyweights = new HashMap<>();public Flyweight getFlyweight(String color) {if (!flyweights.containsKey(color)) {flyweights.put(color, new ConcreteFlyweight(color));}return flyweights.get(color);}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/193651.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

构建第一个ArkTS应用(纯HarmonyOS应用)

1. 安装开发工具 在华为开发者官方上下载HarmonyOS应用专用的开发工具&#xff0c;链接地址&#xff1a;HUAWEI DevEco Studio和SDK下载和升级 | HarmonyOS开发者 要想使用开发工具让项目跑起来&#xff0c;需要10G的磁盘空间。开发工具需要的磁盘空间为2.36G&#xff1b;SDK需…

WT2003H语音芯片系列:通过bin文件实现板载语音更新,支持宽范围音频码率

随着科技的飞速发展&#xff0c;语音芯片已经成为了许多电子产品不可或缺的一部分。在这个领域中&#xff0c;WT2003H语音芯片系列以其卓越的性能和灵活的功能而备受瞩目。这一系列芯片具备一种独特的功能&#xff0c;即可以通过bin文件在板更新语音&#xff0c;同时音频码率支…

深度学习记录--logistic回归函数的计算图

计算图用于logistic回归函数 先回顾一下单一样本的logistic回归损失函数的公式&#xff0c;公式如下&#xff1a; 将logistic函数用计算图表示出来(以两个基础量为例)&#xff0c;计算图如下&#xff1a; 前向传播已经完成&#xff0c;接下来完成后向传播 运用链式法则依次求…

The Big IAM Challenge 云安全 CTF 挑战赛

The Big IAM Challenge 云安全 CTF 挑战赛 今天&#xff0c;我们来做一下有关于云安全 的CTF 挑战赛 The Big IAM Challenge,旨在让白帽子识别和利用 IAM错误配置&#xff0c;并从现实场景中学习&#xff0c;从而更好的认识和了解IAM相关的风险。比赛包括6个场景&#xff0c;每…

LeetCode 232.用栈实现队列

题目 请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作&#xff08;push、pop、peek、empty&#xff09;&#xff1a; 实现 MyQueue 类&#xff1a; void push(int x) 将元素 x 推到队列的末尾 int pop() 从队列的开头移除并返回元素 int peek() 返回…

智跃人力资源管理系统GenerateEntityFromTable.aspx接口存在SQL注入漏洞 附POC

@[toc] 智跃人力资源管理系统GenerateEntityFromTable.aspx接口存在SQL注入漏洞 附POC 免责声明:请勿利用文章内的相关技术从事非法测试,由于传播、利用此文所提供的信息或者工具而造成的任何直接或者间接的后果及损失,均由使用者本人负责,所产生的一切不良后果与文章作者…

别再争国漫一哥了,真正的王者回来了!

相信很多漫迷都知道&#xff0c;《斗罗大陆》动画在播出的五年期间一直稳稳占领国漫各榜单第一的位置。现在它已经完结了大半年&#xff0c;尽管《斗破苍穹》《完美世界》等动画都在争国漫一哥&#xff0c;但排名总是上下浮动&#xff0c;没有定论。 但就在今天&#xff0c;《斗…

用GPT4.0对csdn问答社区内容进行总结的对话记录(20231203号)

问题链接&#xff1a;微信小游戏开发2D碰撞检测问题 问题内容&#xff1a; 用户在开发微信小游戏的2D项目时遇到了碰撞检测无效的问题。他们尝试使用其他的碰撞类&#xff0c;但在2D中会报错。用户怀疑微信小游戏的框架可能不支持2D碰撞检测&#xff0c;或者需要自己计算和编…

flink获取kafka的key value timestamp header

参考&#xff1a; http://t.csdnimg.cn/FvqEn

JUC-AQS

如何利用CAS实现一个同步框架 state&#xff1a;共享标记位。利用CAS修改&#xff0c;达到同步管理等待队列&#xff1a;存储需要等待获取锁的线程 共享标记位state0 表示资源是空闲的&#xff1b;state1表示有1个线程获取到资源&#xff0c;如何独占模式&#xff0c;判断持有…

一款充电桩解决方案设计

一、基本的概述 项目由IP6536提供两路5V 1.5A 的USB充电口&#xff0c;IP6505提供一路最大24W的USB快充口支持QC3.0 / DCP / QC2.0 / MTK PE1.1 / PE2.0 / FCP / SCP / AFC / SFCP的快充协议&#xff0c;电池充电由type-C输入经过IP2326输出最高15W快充对电池进行充电&#xf…

C++:异常

文章目录 传统的处理错误的方式C异常C异常的使用抛异常的举例异常的重新抛出异常规范 自定义异常体系C标准库中的异常体系异常的优缺点 本篇总结的是C中关于异常的内容 传统的处理错误的方式 在C语言中&#xff0c;对于传统的错误方式有 终止程序&#xff1a;例如assert&…

上海市计算机学会竞赛2023年11月月赛丙组

1.刷题 #include<iostream> using namespace std; int main(){int n,m,a;cin>>n>>m;if(n%m!0){an/m1;}if(n%m0){an/m;}cout<<a; } 2.染色 #include<iostream> #include<algorithm> using namespace std; long long a[300010]; int main…

【STL】手撕 string类

目录 1&#xff0c;string类框架 2&#xff0c;string&#xff08;构造&#xff09; 3&#xff0c;~string&#xff08;析构&#xff09; 4&#xff0c;swap&#xff08;交换&#xff09; 5&#xff0c;string&#xff08;拷贝构造&#xff09; 1&#xff0c;常规法 2&a…

pythonanywhere 介绍

最近因为工作需要用到类似Azure Function App的服务&#xff0c;不过Azure Function App服务需要购买Azure VM&#xff0c;不是免费的。在stackoverflow上刚好看到有人提到pythonanywhere提供类似Azure Function App的服务&#xff0c;而且可以免费使用三个月。 首先申请一个免…

Cmkae外部依赖管理

文章目录 一、cmake依赖管理介绍二、源码依管理1. FetchContent与find_package进行集成 2. CPM3. git submodule附加&#xff1a; address_sanitizer 和 undefined sanitizer 一、cmake依赖管理介绍 CMake 是跨平台的构建系统&#xff0c;支持 C/C、Objective-C、Fortran 等多种…

Git Bash环境下用perl脚本获取uuid值

在Linux环境下&#xff0c;比如在ubuntu就直接有uuidgen命令直接获取uuid值。在Windows环境下常用的git bash中没有对应的命令&#xff0c;略有不便。这里用脚本写一个uuidgen&#xff0c;模拟Linux环境下的uuidgen命令。 #! /usr/bin/perl use v5.14; use Win32;sub uuidGen {…

6-13连接两个字符串

#include<stdio.h> int main(){int i0,j0;char s1[222],s2[333];printf("请输入第一个字符串&#xff1a;\n");gets(s1);//scanf("%s",s1);printf("请输入第二个字符串&#xff1a;\n");gets(s2);while(s1[i]!\0)i;while(s2[j]!\0)s1[i]s2…

1.1卷积的作用

上图解释了1∗1卷积如何适用于尺寸为H∗W∗D的输入层&#xff0c;滤波器大小为1∗1∗D&#xff0c;输出通道的尺寸为H∗W∗1。如果应用n个这样的滤波器&#xff0c;然后组合在一起&#xff0c;得到的输出层大小为H∗W∗n。 1.1∗1卷积的作用 调节通道数 由于 11 卷积并不会改…

webpack查找配置文件的策略

Webpack 在执行时会按照一定的策略来查找配置文件。以下是它查找配置文件的基本流程&#xff1a; 1.命令行指定&#xff1a; 如果在运行 Webpack 时通过 --config 或 -c 参数指定了配置文件的路径&#xff0c;那么 Webpack 将使用这个指定的配置文件。 2.默认查找顺序&…