当前位置: 首页 > news >正文

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 Product {void use();
}// 具体产品类
public class ConcreteProduct implements Product {@Overridepublic void use() {System.out.println("Using ConcreteProduct");}
}// 工厂类
public class Factory {public Product createProduct() {return new ConcreteProduct();}
}// 客户端代码
public class Main {public static void main(String[] args) {Factory factory = new Factory();Product product = factory.createProduct();product.use();}
}

3. 观察者模式 (Observer Pattern)

观察者模式定义了对象之间的一对多依赖,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新。

示例代码
import java.util.ArrayList;
import java.util.List;// 观察者接口
interface Observer {void update(String message);
}// 具体观察者类
class ConcreteObserver implements Observer {private String name;public ConcreteObserver(String name) {this.name = name;}@Overridepublic void update(String message) {System.out.println(name + " received: " + message);}
}// 被观察者接口
interface Subject {void registerObserver(Observer observer);void removeObserver(Observer observer);void notifyObservers();
}// 具体被观察者类
class ConcreteSubject implements Subject {private List<Observer> observers = new ArrayList<>();private String message;public void setMessage(String message) {this.message = message;notifyObservers();}@Overridepublic void registerObserver(Observer observer) {observers.add(observer);}@Overridepublic void removeObserver(Observer observer) {observers.remove(observer);}@Overridepublic void notifyObservers() {for (Observer observer : observers) {observer.update(message);}}
}// 客户端代码
public class Main {public static void main(String[] args) {ConcreteSubject subject = new ConcreteSubject();Observer observer1 = new ConcreteObserver("Observer 1");Observer observer2 = new ConcreteObserver("Observer 2");subject.registerObserver(observer1);subject.registerObserver(observer2);subject.setMessage("Hello, Observers!");}
}

4. 策略模式 (Strategy Pattern)

策略模式定义了算法家族,并且使它们之间可以互相替换。策略模式让算法的变化独立于使用算法的客户。

示例代码
// 策略接口
interface Strategy {int doOperation(int num1, int num2);
}// 具体策略类
class Addition implements Strategy {@Overridepublic int doOperation(int num1, int num2) {return num1 + num2;}
}class Subtraction implements Strategy {@Overridepublic 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);}
}// 客户端代码
public class Main {public static void main(String[] args) {Context context = new Context(new Addition());System.out.println("10 + 5 = " + context.executeStrategy(10, 5));context = new Context(new Subtraction());System.out.println("10 - 5 = " + context.executeStrategy(10, 5));}
}

5. 装饰者模式 (Decorator Pattern)

装饰者模式动态地将责任附加到对象上。装饰者提供了比继承更有弹性的替代方案。

示例代码
// 组件接口
interface Component {void operation();
}// 具体组件类
class ConcreteComponent implements Component {@Overridepublic void operation() {System.out.println("ConcreteComponent operation");}
}// 装饰者抽象类
abstract class Decorator implements Component {protected Component component;public Decorator(Component component) {this.component = component;}public void operation() {component.operation();}
}// 具体装饰者类
class ConcreteDecorator extends Decorator {public ConcreteDecorator(Component component) {super(component);}@Overridepublic void operation() {super.operation();addedBehavior();}private void addedBehavior() {System.out.println("ConcreteDecorator added behavior");}
}// 客户端代码
public class Main {public static void main(String[] args) {Component component = new ConcreteComponent();Component decorator = new ConcreteDecorator(component);decorator.operation();}
}

总结

以上是一些常用设计模式的入门介绍及其Java实现示例。掌握这些设计模式有助于编写更加可维护、灵活和高效的代码。设计模式不仅仅是代码模板,更是一种思维方式,可以帮助开发者在面临复杂问题时找到最佳解决方案。通过不断的学习和实践,可以更好地理解和应用这些设计模式。

http://www.lryc.cn/news/373419.html

相关文章:

  • 110.平衡二叉树
  • 字符串数组——传递文本的不同方法实例
  • JDBC简介
  • RK3568平台(触摸篇)触摸屏基本原理
  • 【太原理工大学】软件系统安全—分析题
  • 【仪器仪表/电源专题】浮地信号的测试的四种方案对比
  • Centos7安装jdk8或11以及切换方案
  • 计算机二级Access选择题考点—代码篇
  • 海外仓系统如何让海外仓受益,WMS海外仓系统使用指南
  • 贪心-区间问题
  • 算法分析与设计期末考试复习GDPU
  • 分批次训练和评估神经网络模型
  • 【CS.AL】算法核心之分治算法:从入门到进阶
  • leetcode刷题记录:hot100强化训练2:二叉树+图论
  • 湘潭大学信息与网络安全复习笔记2(总览)
  • C语言:头歌使用函数找出数组中的最大值
  • 【技巧】Leetcode 191. 位1的个数【简单】
  • 【Pandas驯化-02】pd.read_csv读取中文出现error解决方法
  • linux下C语言如何操作文件(三)
  • 6.14作业
  • MySQL数据库管理(一)
  • Kafka使用教程和案例详解
  • TGI模型- 同期群-评论文本
  • ESP32 BLE学习(0) — 基础架构
  • 【JAVA】Java中Spring Boot如何设置全局的BusinessException
  • pdf.js实现web h5预览pdf文件(兼容低版本浏览器)
  • SSID简介
  • PS通过GTX实现SFP网络通信1
  • 前端面试项目细节重难点(已工作|做分享)(九)
  • 区间预测 | Matlab实现BP-ABKDE的BP神经网络自适应带宽核密度估计多变量回归区间预测