JAVA的设计模式都有那些

        Java设计模式是为了解决软件开发中常见的问题而创建的一系列最佳实践。它们提供了一种在特定情境下解决问题的方法论,并且已经被广泛验证和应用。这些模式不是具体的代码,而是关于如何组织代码以达到某种目的的高层次描述。设计模式通常分为三大类:创建型模式、结构型模式和行为型模式。

一  创建型模式

这类模式主要处理对象的创建方式,目的是将系统与具体类解耦。

       1. 单例模式 (Singleton Pattern)

                 确保一个类只有一个实例,并提供一个全局访问点。例如,数据库连接池或日志记录器。

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

       2. 工厂方法模式 (Factory Method Pattern)

                定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。工厂方法让类把实例化推迟到子类。

interface Product { void use(); }class ConcreteProduct implements Product { public void use() {} }abstract class Creator {public final Product create(String type) {Product product = factoryMethod(type);// 准备、初始化等return product;}protected abstract Product factoryMethod(String type);
}class ConcreteCreator extends Creator {protected Product factoryMethod(String type) {if ("A".equals(type)) {return new ConcreteProduct();} else {throw new IllegalArgumentException("Invalid product type");}}
}

       3. 抽象工厂模式 (Abstract Factory Pattern)

                提供一个接口来创建一系列相关或相互依赖的对象,而无需指定它们的具体类。

interface AbstractFactory {ProductA createProductA();ProductB createProductB();
}class ConcreteFactory1 implements AbstractFactory {public ProductA createProductA() { return new ConcreteProductA1(); }public ProductB createProductB() { return new ConcreteProductB1(); }
}// 其他产品和工厂实现...

       4. 建造者模式 (Builder Pattern)

                将复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。

class Product {// 复杂对象属性
}interface Builder {void buildPartA();void buildPartB();Product getResult();
}class ConcreteBuilder implements Builder {private Product product = new Product();public void buildPartA() { /* 构建部分A */ }public void buildPartB() { /* 构建部分B */ }public Product getResult() { return product; }
}class Director {private Builder builder;public Director(Builder builder) { this.builder = builder; }public void construct() {builder.buildPartA();builder.buildPartB();}
}

       5. 原型模式 (Prototype Pattern)

                通过复制现有实例来创建新实例,而不是通过构造函数创建。

interface Prototype {Prototype clone();
}class ConcretePrototype implements Prototype, Cloneable {@Overridepublic Prototype clone() {try {return (ConcretePrototype) super.clone();} catch (CloneNotSupportedException e) {throw new AssertionError();}}
}

二  结构型模式

         结构型模式关注于如何组合类和对象以形成更大的结构,同时保持结构的灵活性和高效性。

       1. 适配器模式 (Adapter Pattern)

                允许不兼容接口的对象能够一起工作。

interface Target {void request();
}class Adaptee {void specificRequest() {}
}class Adapter implements Target {private Adaptee adaptee;public Adapter(Adaptee adaptee) { this.adaptee = adaptee; }public void request() { adaptee.specificRequest(); }
}

       2. 桥接模式 (Bridge Pattern)

                将抽象部分与它的实现部分分离,使它们都可以独立地变化。

interface Implementor {void operationImpl();
}class ConcreteImplementorA implements Implementor {public void operationImpl() { /* 实现细节 */ }
}abstract class Abstraction {protected Implementor implementor;public void setImplementor(Implementor implementor) {this.implementor = implementor;}public abstract void operation();
}class RefinedAbstraction extends Abstraction {public void operation() {implementor.operationImpl();}
}

       3. 装饰器模式 (Decorator Pattern)

                动态地给一个对象添加一些额外的职责。

interface Component {void operation();
}class ConcreteComponent implements Component {public void operation() { /* 基本功能 */ }
}abstract class Decorator implements Component {protected Component component;public Decorator(Component component) {this.component = component;}public void operation() {component.operation();}
}class ConcreteDecoratorA extends Decorator {public ConcreteDecoratorA(Component component) { super(component); }public void addedBehavior() { /* 额外的行为 */ }public void operation() {super.operation();addedBehavior();}
}

       4. 外观模式 (Facade Pattern)

                提供了一个统一的接口,用来访问子系统中的一群接口。

class Subsystem1 { public void operation1() {} }
class Subsystem2 { public void operation2() {} }
class Subsystem3 { public void operation3() {} }class Facade {private Subsystem1 subsystem1;private Subsystem2 subsystem2;private Subsystem3 subsystem3;public Facade() {subsystem1 = new Subsystem1();subsystem2 = new Subsystem2();subsystem3 = new Subsystem3();}public void operation() {subsystem1.operation1();subsystem2.operation2();subsystem3.operation3();}
}

       5. 享元模式 (Flyweight Pattern)

                用于减少创建对象的数量,以减少内存占用并提高性能。

interface Flyweight {void operation(int extrinsicState);
}class ConcreteFlyweight implements Flyweight {private int intrinsicState;public ConcreteFlyweight(int intrinsicState) {this.intrinsicState = intrinsicState;}public void operation(int extrinsicState) {System.out.println("Intrinsic State: " + intrinsicState + ", Extrinsic State: " + extrinsicState);}
}class FlyweightFactory {private Map<Integer, ConcreteFlyweight> flyweights = new HashMap<>();public Flyweight getFlyweight(int key) {if (!flyweights.containsKey(key)) {flyweights.put(key, new ConcreteFlyweight(key));}return flyweights.get(key);}
}

       6. 代理模式 (Proxy Pattern)

                为其他对象提供一种代理以控制对这个对象的访问。

interface Subject {void request();
}class RealSubject implements Subject {public void request() { /* 实际操作 */ }
}class Proxy implements Subject {private RealSubject realSubject;public void request() {if (realSubject == null) {realSubject = new RealSubject();}preRequest();realSubject.request();postRequest();}private void preRequest() { /* 在请求前执行的操作 */ }private void postRequest() { /* 在请求后执行的操作 */ }
}

       7. 组合模式 (Composite Pattern)

                允许你将对象组合成树形结构来表示“部分-整体”的层次结构。

interface Component {void add(Component c);void remove(Component c);void display(int depth);
}class Leaf implements Component {public void add(Component c) { throw new UnsupportedOperationException(); }public void remove(Component c) { throw new UnsupportedOperationException(); }public void display(int depth) { for (int i = 0; i < depth; i++) { System.out.print("-"); } System.out.println("Leaf"); }
}class Composite implements Component {private List<Component> children = new ArrayList<>();public void add(Component c) { children.add(c); }public void remove(Component c) { children.remove(c); }public void display(int depth) {for (int i = 0; i < depth; i++) { System.out.print("-"); }System.out.println("+ Composite");for (Component child : children) {child.display(depth + 1);}}
}

三  行为型模式

         行为型模式涉及对象之间的通信和协作,以及分配责任和算法的方式。

       1. 策略模式 (Strategy Pattern)

                定义了一系列可互换的算法,并将每个算法封装起来,使得算法的变化独立于使用算法的客户。

interface Strategy {int doOperation(int num1, int num2);
}class OperationAdd implements Strategy {public int doOperation(int num1, int num2) { return num1 + num2; }
}class Context {private Strategy strategy;public Context(Strategy strategy) { this.strategy = strategy; }public int executeStrategy(int num1, int num2) {return strategy.doOperation(num1, num2);}
}

       2. 观察者模式 (Observer Pattern)

                当一个对象的状态改变时,所有依赖它的对象都会收到通知并自动更新。

interface Observer {void update(String message);
}interface Subject {void attach(Observer observer);void detach(Observer observer);void notifyObservers(String message);
}class ConcreteSubject implements Subject {private List<Observer> observers = new ArrayList<>();public void attach(Observer observer) { observers.add(observer); }public void detach(Observer observer) { observers.remove(observer); }public void notifyObservers(String message) {for (Observer observer : observers) {observer.update(message);}}
}class ConcreteObserver implements Observer {public void update(String message) { System.out.println("Received: " + message); }
}

       3. 命令模式 (Command Pattern)

                将请求封装为一个对象,从而使你可以用不同的请求对客户进行参数化。

interface Command {void execute();
}class ConcreteCommand implements Command {private Receiver receiver;public ConcreteCommand(Receiver receiver) { this.receiver = receiver; }public void execute() { receiver.action(); }
}class Receiver {public void action() { /* 执行实际动作 */ }
}class Invoker {private Command command;public void setCommand(Command command) { this.command = command; }public void executeCommand() { command.execute(); }
}

       4. 状态模式 (State Pattern)

                允许一个对象在其内部状态改变时改变其行为。

interface State {void handle(Context context);
}class ConcreteStateA implements State {public void handle(Context context) {context.setState(new ConcreteStateB());System.out.println("Switch to State B");}
}class ConcreteStateB implements State {public void handle(Context context) {context.setState(new ConcreteStateA());System.out.println("Switch to State A");}
}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); }
}

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

                定义了一个算法的骨架,而将一些步骤延迟到子类中。

abstract class AbstractClass {public final void templateMethod() {primitiveOperation1();primitiveOperation2();}protected abstract void primitiveOperation1();protected abstract void primitiveOperation2();
}class ConcreteClass extends AbstractClass {protected void primitiveOperation1() { /* 实现操作1 */ }protected void primitiveOperation2() { /* 实现操作2 */ }
}

       6. 中介者模式 (Mediator Pattern)

                 用一个中介对象来封装一系列的对象交互。

interface Mediator {void notify(Object sender, String ev);
}class ConcreteMediator implements Mediator {private Component1 component1;private Component2 component2;public ConcreteMediator(Component1 c1, Component2 c2) {this.component1 = c1;this.component2 = c2;}public void notify(Object sender, String ev) {if (ev.equals("A")) {component2.doC();} else if (ev.equals("D")) {component1.doB();}}
}class Component1 {private Mediator mediator;public Component1(Mediator mediator) { this.mediator = mediator; }public void doA() { mediator.notify(this, "A"); }public void doB() { System.out.println("Doing B"); }
}class Component2 {private Mediator mediator;public Component2(Mediator mediator) { this.mediator = mediator; }public void doC() { System.out.println("Doing C"); }public void doD() { mediator.notify(this, "D"); }
}

       7. 迭代器模式 (Iterator Pattern)

                提供一种方法顺序访问一个聚合对象中的各个元素,而又不需要暴露该对象的内部表示。

interface Iterator {boolean hasNext();Object next();
}interface Container {Iterator getIterator();
}class NameRepository implements Container {public String names[] = {"Robert", "John", "Julie", "Lora"};public Iterator getIterator() {return new NameIterator();}private class NameIterator implements Iterator {int index;public boolean hasNext() {if (index < names.length) {return true;}return false;}public Object next() {if (this.hasNext()) {return names[index++];}return null;}}
}

       8. 访问者模式 (Visitor Pattern)

                在不改变数据结构的前提下,增加作用于一组对象元素的新功能。

interface Element {void accept(Visitor v);
}interface Visitor {void visitConcreteElementA(ConcreteElementA a);void visitConcreteElementB(ConcreteElementB b);
}class ConcreteElementA implements Element {public void accept(Visitor v) { v.visitConcreteElementA(this); }public void operationA() { /* 操作A */ }
}class ConcreteElementB implements Element {public void accept(Visitor v) { v.visitConcreteElementB(this); }public void operationB() { /* 操作B */ }
}class ConcreteVisitor1 implements Visitor {public void visitConcreteElementA(ConcreteElementA a) { a.operationA(); }public void visitConcreteElementB(ConcreteElementB b) { b.operationB(); }
}class ConcreteVisitor2 implements Visitor {public void visitConcreteElementA(ConcreteElementA a) { a.operationA(); }public void visitConcreteElementB(ConcreteElementB b) { b.operationB(); }
}

        以上只是每种设计模式的一个简单示例。在实际开发过程中,你需要根据具体的需求和场景选择合适的设计模式。设计模式不仅帮助解决常见问题,还促进了代码复用、增强了程序的可维护性和扩展性。理解并熟练运用这些模式,可以帮助开发者编写出更加优雅和高效的代码。

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

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

相关文章

一致校验矩阵计算

目录 T1T2T3 T1 设二元(7,4)码的生成矩阵为&#xff1a; G [ 1 0 0 0 1 1 1 0 1 0 0 1 0 1 0 0 1 0 0 1 1 0 0 0 1 1 1 0 ] G\begin{bmatrix}1&0&0&0&1&1&1\\0&1&0&0&1&0&1\\0&0&1&0&0&1&1\\0&…

数学建模与优化算法:从基础理论到实际应用

数学建模和优化算法&#xff0c;它们不仅帮助我们理解和描述复杂系统的行为&#xff0c;还能找到系统性能最优化的解决方案。本文将从基础的数学理论出发&#xff0c;逐步深入到各种优化算法&#xff0c;并探讨它们在实际问题中的应用。 思维导图文件可获取&#xff1a;https:…

关于使用K8s实现容器化作业的总时效最优调度

一、Kubernetes对总时效最优调度实现的情况 Kubernetes 可以帮助实现一定程度的时效性优化&#xff0c;但要达到“总时效性最优”还需要一些额外的配置和调度策略。以下是一些可以提升整体时效性的策略&#xff1a; 1. 资源请求和限制设置 为每个容器设置合适的资源请求和限制…

判断对象、数组的方法

判断对象的方法 Object.prototype.toString.call(obj) ‘[object Object]’ 推荐指数 &#xff1a;五颗星obj instanceof Object 推荐指数 &#xff1a;四颗星typeof obj Object 推荐指数 &#xff1a;三颗星 注意&#xff1a;null也是一个对象 typeof(null) Object obj…

基于Intel Gaudi AI加速器的大语言模型微调与推理优化赛题等你挑战 | CCF BDCI进行时

一年一度的行业盛事2024 CCF大数据与计算智能大赛&#xff08;简称2024 CCF BDCI&#xff09;又在激烈进行中啦&#xff01; 多个赛题等你挑战还没有报名的伙伴们抓紧时间咯&#xff0c;叫上你伙伴练起来吧&#xff01; 2024 CCF大数据与计算智能大赛 CCF大数据与计算智能大…

使用 FastGPT 工作流搭建 GitHub Issues 自动总结机器人

如今任何项目开发节奏都很快&#xff0c;及时掌握项目动态是很重要滴&#xff0c;GitHub Issues 一般都是开发者和用户反馈问题的主要渠道。 然而&#xff0c;随着 Issue 数量的增加&#xff0c;及时跟进每一个问题会变得越来越困难。 为了解决这个痛点&#xff0c;我们开发了…

GEE 高阶应用:下载全球任何国家的森林损失保存到assets中

目录 简介 数据 函数 filterMetadata(name, operator, value) Arguments: Returns: Collection aggregate_array(property) Arguments: Returns: List ee.Number.parse(input, radix) Arguments: Returns: Number clipToCollection(collection) Arguments: Retu…

C++ 在项目中使用vim

一&#xff1a;概述 除了掌握 Vim 的基本操作&#xff0c;利用 Vim 阅读项目源码的方法同样重要&#xff0c;这对实际项目开发大有裨益。虽然现在有许多人选择使用 VSCode&#xff0c;但在某些环境中&#xff0c;可能无法安装 VSCode 或联网下载插件&#xff0c;这时使用 Vim 就…

Unreal Engine 5 C++(C#)开发:使用蓝图库实现插件(一)认识和了解Build.cs

目录 引言 一、创建一个C插件TextureReader插件 二、Build.cs文件 三、ModuleRules 四、TextureReader插件的构造 4.1ReadOnlyTargetRules的作用 4.2TextureReaderd的构造调用 4.3设置当前类的预编译头文件的使用模式 4.4PublicIncludePaths.AddRange与PrivateInclude…

探索C嘎嘎:初步接触STL

#1024程序员节&#xff5c;征文# 前言&#xff1a; 在前文小编讲述了模版初阶&#xff0c;其实讲述模版就是为了给讲STL提前铺垫&#xff0c;STL是C中很重要的一部分&#xff0c;各位读者朋友要知道它的份量&#xff0c;下面废话不多说&#xff0c;开始走进STL的世界。 目录&am…

指令系统 I(指令的格式、寻址)

一、指令系统 1. 指令集体系结构 指令&#xff08;机器指令&#xff09;是指示计算机执行某种操作的命令&#xff0c;是计算机运行的最小功能单位。一台计算机的所有指令的集合构成该机的指令系统&#xff0c;也称指令集。 指令系统是指令集体系结构&#xff08;ISA&#xf…

说一说QWidget

目录 关于QWidget 作为界面组件时&#xff0c;你需要有印象的 1. 控制属性 2. 组件状态与交互属性 3. 外观和样式属性 4. 布局与子组件管理属性 5. 图标和光标属性 6. 大小策略属性 作为单独的窗体的属性 写Qt快两年了&#xff0c;也写过一些规模偏大的软件&#xff0c…

刘艳兵-DBA015-对于属于默认undo撤销表空间的数据文件的丢失,哪条语句是正确的?

对于属于默认undo撤销表空间的数据文件的丢失&#xff0c;哪条语句是正确的&#xff1f; A 所有未提交的交易都将丢失。 B 数据库实例中止。 C 数据库处于MOUNT状态&#xff0c;需要恢复才能打开。 D 数据库保持打开状态以供查询&#xff0c;但除具有SYSDBA特权的用…

如何精准选择Yandex关键词

Hey小伙伴们&#x1f44b;&#xff0c;今天来聊聊如何精准选择Yandex关键词&#xff0c;让你的广告投放效果最大化&#xff01;&#x1f50d; 1.使用Yandex关键词工具&#xff1a;Yandex提供了关键词工具&#xff0c;如Yandex Keyword Planner和Yandex Wordstat&#xff0…

快速生成高质量提示词,Image to Prompt 更高效

抖知书老师推荐&#xff1a; 随着 AI 技术的不断发展&#xff0c;视觉信息与语言信息之间的转换变得越来越便捷。在如今的数字化生活中&#xff0c;图像与文字的交互需求愈发旺盛&#xff0c;很多人都希望能轻松将图像内容直接转化为文本描述。今天我们来推荐一款实用的 AI 工…

go语言回调函数的使用

前言 在 Go 语言中&#xff0c;回调函数是一种将一个函数作为参数传递给另一个函数&#xff0c;在特定的事件发生时被调用的编程模式。 一、回调函数的定义 type OnTaskHandler func(r []byte)type remoteTaskClient struct {sync.RWMutexonTask OnTaskHandler } 以上定义了…

Kubernetes(k8s)挂载hostPath和emptyDir两种volume的区别

Kubernetes挂载可以指定多种类型的volume&#xff0c;这篇文章聊一下hostPath和emptyDir两种volume的区别。 hostPath类型是将宿主机的目录或者文件挂载到容器中&#xff0c;这样容器写入和读取的数据是直接反映在宿主机上的&#xff0c;这种方式产生的数据可以在不同pod之间共…

jmeter附件上传

可以采用录制的方式获取附件上传的http请求 普通参数 附件参数 文件名称: 方式一:如果只添项目名称,默认充jmeter的bin目录下获取 方式二:点击文件名称,再点击浏览,可以自己选择文件信息

OpenCV视觉分析之目标跟踪(7)目标跟踪器类TrackerVit的使用

操作系统&#xff1a;ubuntu22.04 OpenCV版本&#xff1a;OpenCV4.9 IDE:Visual Studio Code 编程语言&#xff1a;C11 算法描述 VIT 跟踪器由于特殊的模型结构而变得更快且极其轻量级&#xff0c;模型文件大约为 767KB。模型下载链接&#xff1a;https://github.com/opencv/…

如何用Python同时抓取多个网页:深入ThreadPoolExecutor

背景介绍 在信息化时代&#xff0c;数据的实时性和获取速度是其核心价值所在。对于体育赛事爱好者、数据分析师和投注行业而言&#xff0c;能否快速、稳定地抓取到实时比赛信息显得尤为重要。特别是在五大足球联赛中&#xff0c;能够在比赛进行时获得比分、控球率等实时数据&a…