設計模式實戰指南:從源碼解析到Java后端架構的藝術

🎯 設計模式實戰指南:從源碼解析到Java后端架構的藝術

概述

本文檔基于設計模式分類,詳細介紹Java后端開發中各種設計模式的實際應用場景,結合Spring、MyBatis、Redis等主流框架的源碼分析,幫助開發者深入理解設計模式在實踐中的價值。

一、創建型模式

1. 單例模式(Singleton Pattern)

應用場景
  • 數據庫連接池
  • 緩存管理器
  • 配置管理器
  • 日志記錄器
Spring框架中的應用

Spring IoC容器本身就是單例模式的典型應用

// Spring ApplicationContext 單例實現
public class AnnotationConfigApplicationContext extends GenericApplicationContext {private final AnnotatedBeanDefinitionReader reader;private final ClassPathBeanDefinitionScanner scanner;public AnnotationConfigApplicationContext() {this.reader = new AnnotatedBeanDefinitionReader(this);this.scanner = new ClassPathBeanDefinitionScanner(this);}
}

Spring Bean的默認作用域就是單例

// Spring BeanFactory 中的單例管理
public class DefaultSingletonBeanRegistry extends FactoryBeanRegistrySupport {// 單例對象緩存private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);protected Object getSingleton(String beanName, boolean allowEarlyReference) {Object singletonObject = this.singletonObjects.get(beanName);if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {// 單例創建邏輯}return singletonObject;}
}
Redis客戶端單例應用
// JedisPool 單例模式實現
public class RedisManager {private static volatile JedisPool jedisPool;public static JedisPool getInstance() {if (jedisPool == null) {synchronized (RedisManager.class) {if (jedisPool == null) {JedisPoolConfig config = new JedisPoolConfig();config.setMaxTotal(100);config.setMaxIdle(10);jedisPool = new JedisPool(config, "localhost", 6379);}}}return jedisPool;}
}

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

應用場景
  • 數據庫連接工廠
  • 消息隊列工廠
  • 緩存工廠
  • 序列化器工廠
Spring框架中的應用

BeanFactory - Spring的核心工廠

// Spring BeanFactory 接口
public interface BeanFactory {Object getBean(String name) throws BeansException;<T> T getBean(String name, Class<T> requiredType) throws BeansException;<T> T getBean(Class<T> requiredType) throws BeansException;
}// 具體實現類
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactoryimplements ConfigurableListableBeanFactory, BeanDefinitionRegistry {@Overridepublic <T> T getBean(Class<T> requiredType) throws BeansException {return getBean(requiredType, (Object[]) null);}
}
MyBatis中的工廠應用
// MyBatis SqlSessionFactory
public interface SqlSessionFactory {SqlSession openSession();SqlSession openSession(boolean autoCommit);SqlSession openSession(Connection connection);
}// 默認實現
public class DefaultSqlSessionFactory implements SqlSessionFactory {@Overridepublic SqlSession openSession() {return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);}
}

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

應用場景
  • 數據庫訪問層抽象
  • 消息中間件抽象
  • 緩存系統抽象
Spring JDBC中的應用
// 數據源抽象工廠
public interface DataSource extends CommonDataSource, Wrapper {Connection getConnection() throws SQLException;Connection getConnection(String username, String password) throws SQLException;
}// 具體實現
public class HikariDataSource extends HikariConfig implements DataSource {@Overridepublic Connection getConnection() throws SQLException {return getConnection(username, password);}
}

4. 建造者模式(Builder Pattern)

應用場景
  • 復雜對象構建
  • 配置對象構建
  • 查詢條件構建
MyBatis中的應用
// MyBatis SqlSessionFactoryBuilder
public class SqlSessionFactoryBuilder {public SqlSessionFactory build(InputStream inputStream) {return build(inputStream, null, null);}public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {try {XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);return build(parser.parse());} catch (Exception e) {throw ExceptionFactory.wrapException("Error building SqlSession.", e);}}
}
Spring Boot配置構建
// Spring Boot ApplicationBuilder
public class SpringApplicationBuilder {private final SpringApplication application;public SpringApplicationBuilder(Class<?>... sources) {this.application = new SpringApplication(sources);}public SpringApplicationBuilder properties(String... defaultProperties) {this.application.setDefaultProperties(StringUtils.toStringArray(defaultProperties));return this;}
}

5. 原型模式(Prototype Pattern)

應用場景
  • 對象克隆
  • 配置復制
  • 模板復制
Spring中的應用
// Spring Bean的prototype作用域
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory {@Overridepublic Object getBean(String name) throws BeansException {return doGetBean(name, null, null, false);}protected <T> T doGetBean(String name, Class<T> requiredType, Object[] args, boolean typeCheckOnly) {// 對于prototype作用域的bean,每次都創建新實例if (mbd.isPrototype()) {Object prototypeInstance = null;try {beforePrototypeCreation(beanName);prototypeInstance = createBean(beanName, mbd, args);} finally {afterPrototypeCreation(beanName);}bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);}}
}

二、結構型模式

1. 適配器模式(Adapter Pattern)

應用場景
  • 接口適配
  • 數據格式轉換
  • 第三方庫集成
Spring MVC中的應用
// HandlerAdapter 適配不同類型的處理器
public interface HandlerAdapter {boolean supports(Object handler);ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception;
}// RequestMappingHandlerAdapter 適配 @RequestMapping 注解的處理器
public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter {@Overridepublic boolean supports(Object handler) {return handler instanceof HandlerMethod;}@Overrideprotected ModelAndView handleInternal(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {// 處理邏輯}
}
MyBatis中的適配器
// MyBatis TypeHandler 適配器
public interface TypeHandler<T> {void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;T getResult(ResultSet rs, String columnName) throws SQLException;T getResult(ResultSet rs, int columnIndex) throws SQLException;T getResult(CallableStatement cs, int columnIndex) throws SQLException;
}// 具體實現
public class StringTypeHandler extends BaseTypeHandler<String> {@Overridepublic void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {ps.setString(i, parameter);}@Overridepublic String getNullableResult(ResultSet rs, String columnName) throws SQLException {return rs.getString(columnName);}
}

2. 橋接模式(Bridge Pattern)

應用場景
  • 抽象與實現分離
  • 多維度變化
  • 平臺無關性
JDBC橋接模式
// JDBC驅動橋接
public interface Driver {Connection connect(String url, Properties info) throws SQLException;boolean acceptsURL(String url) throws SQLException;
}// MySQL驅動實現
public class Driver implements java.sql.Driver {@Overridepublic Connection connect(String url, Properties info) throws SQLException {// MySQL連接實現}
}// PostgreSQL驅動實現
public class Driver implements java.sql.Driver {@Overridepublic Connection connect(String url, Properties info) throws SQLException {// PostgreSQL連接實現}
}

3. 組合模式(Composite Pattern)

應用場景
  • 樹形結構
  • 菜單系統
  • 權限管理
Spring Security中的應用
// Spring Security 權限組合
public interface GrantedAuthority extends Serializable {String getAuthority();
}// 角色權限組合
public class SimpleGrantedAuthority implements GrantedAuthority {private final String role;public SimpleGrantedAuthority(String role) {this.role = role;}@Overridepublic String getAuthority() {return this.role;}
}

4. 裝飾器模式(Decorator Pattern)

應用場景
  • 功能增強
  • 緩存裝飾
  • 日志裝飾
Spring AOP裝飾器
// Spring AOP 代理裝飾
public interface AopProxy {Object getProxy();Object getProxy(ClassLoader classLoader);
}// JDK動態代理裝飾
public class JdkDynamicAopProxy implements AopProxy, InvocationHandler {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {// 前置增強// 目標方法調用// 后置增強}
}
MyBatis插件裝飾器
// MyBatis Interceptor 裝飾器
public interface Interceptor {Object intercept(Invocation invocation) throws Throwable;Object plugin(Object target);void setProperties(Properties properties);
}// 分頁插件裝飾器
public class PageInterceptor implements Interceptor {@Overridepublic Object intercept(Invocation invocation) throws Throwable {// 分頁邏輯裝飾return invocation.proceed();}
}

5. 外觀模式(Facade Pattern)

應用場景
  • 復雜子系統封裝
  • API簡化
  • 統一接口
Spring Boot自動配置外觀
// Spring Boot 自動配置外觀
@SpringBootApplication
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}// 內部封裝了復雜的配置過程
public class SpringApplication {public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {return new SpringApplication(primarySources).run(args);}
}

6. 享元模式(Flyweight Pattern)

應用場景
  • 對象池
  • 緩存
  • 字符串常量池
數據庫連接池
// HikariCP 連接池享元模式
public class HikariDataSource extends HikariConfig implements DataSource {private final HikariPool pool;@Overridepublic Connection getConnection() throws SQLException {return pool.getConnection();}
}// 連接池管理
public class HikariPool extends PoolBase {private final ConcurrentBag<PoolEntry> connectionBag;public Connection getConnection() throws SQLException {PoolEntry poolEntry = connectionBag.borrow(connectionTimeout, MILLISECONDS);return poolEntry.createProxyConnection(now(), leakTaskFactory.schedule(poolEntry));}
}

7. 代理模式(Proxy Pattern)

應用場景
  • 遠程代理
  • 虛擬代理
  • 保護代理
  • 緩存代理
Spring AOP代理
// Spring AOP 代理實現
public class ProxyFactory extends ProxyCreatorSupport {public Object getProxy() {return createAopProxy().getProxy();}
}// CGLIB代理
public class CglibAopProxy implements AopProxy {@Overridepublic Object getProxy() {return getProxy(null);}@Overridepublic Object getProxy(ClassLoader classLoader) {// CGLIB代理創建邏輯}
}
MyBatis動態代理
// MyBatis Mapper代理
public class MapperProxy<T> implements InvocationHandler, Serializable {private final SqlSession sqlSession;private final Class<T> mapperInterface;@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {// 動態代理邏輯return sqlSession.selectOne(statement, args);}
}

三、行為型模式

1. 責任鏈模式(Chain of Responsibility Pattern)

應用場景
  • 過濾器鏈
  • 異常處理鏈
  • 權限驗證鏈
Spring Security過濾器鏈
// Spring Security 過濾器鏈
public class FilterChainProxy extends GenericFilterBean {private List<SecurityFilterChain> filterChains;@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {doFilterInternal(request, response, chain);}private void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {// 過濾器鏈執行邏輯for (Filter filter : filters) {filter.doFilter(request, response, chain);}}
}
MyBatis插件鏈
// MyBatis 插件責任鏈
public class Plugin implements InvocationHandler {private final Object target;private final Interceptor interceptor;@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {return interceptor.intercept(new Invocation(target, method, args));}
}

2. 命令模式(Command Pattern)

應用場景
  • 操作封裝
  • 事務管理
  • 異步處理
Spring事務命令
// Spring 事務命令模式
public interface TransactionTemplate {<T> T execute(TransactionCallback<T> action) throws TransactionException;
}// 具體實現
public class TransactionTemplate extends DefaultTransactionDefinition implements TransactionOperations {@Overridepublic <T> T execute(TransactionCallback<T> action) throws TransactionException {TransactionStatus status = this.transactionManager.getTransaction(this);T result;try {result = action.doInTransactionWithoutResult(status);} catch (RuntimeException | Error ex) {rollbackOnException(status, ex);throw ex;}this.transactionManager.commit(status);return result;}
}

3. 解釋器模式(Interpreter Pattern)

應用場景
  • 表達式解析
  • 配置解析
  • 查詢語言解析
MyBatis SQL解析
// MyBatis SQL解析器
public class SqlSourceBuilder {public SqlSource parse(String originalSql, Class<?> parameterType, Map<String, Object> additionalParameters) {ParameterMappingTokenHandler handler = new ParameterMappingTokenHandler(configuration, parameterType, additionalParameters);GenericTokenParser parser = new GenericTokenParser("#{", "}", handler);String sql = parser.parse(originalSql);return new StaticSqlSource(configuration, sql, handler.getParameterMappings());}
}

4. 迭代器模式(Iterator Pattern)

應用場景
  • 集合遍歷
  • 分頁查詢
  • 流式處理
Spring Data分頁迭代
// Spring Data 分頁迭代器
public interface Page<T> extends Slice<T> {int getTotalPages();long getTotalElements();List<T> getContent();
}// 具體實現
public class PageImpl<T> implements Page<T> {private final List<T> content;private final Pageable pageable;private final long total;@Overridepublic Iterator<T> iterator() {return content.iterator();}
}

5. 中介者模式(Mediator Pattern)

應用場景
  • 組件通信
  • 事件處理
  • 協調管理
Spring事件機制
// Spring 事件中介者
public interface ApplicationEventPublisher {void publishEvent(ApplicationEvent event);void publishEvent(Object event);
}// 具體實現
public class SimpleApplicationEventMulticaster extends AbstractApplicationEventMulticaster {@Overridepublic void multicastEvent(ApplicationEvent event) {multicastEvent(event, resolveDefaultEventType(event));}@Overridepublic void multicastEvent(final ApplicationEvent event, ResolvableType type) {// 事件分發邏輯for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {invokeListener(listener, event);}}
}

6. 備忘錄模式(Memento Pattern)

應用場景
  • 狀態保存
  • 事務回滾
  • 撤銷操作
Spring事務狀態管理
// Spring 事務狀態備忘錄
public interface TransactionStatus extends SavepointManager, Flushable {boolean isNewTransaction();boolean hasTransaction();boolean isRollbackOnly();boolean isCompleted();
}// 具體實現
public class DefaultTransactionStatus extends AbstractTransactionStatus {private final Object transaction;private final boolean newTransaction;private boolean rollbackOnly;private boolean completed;
}

7. 觀察者模式(Observer Pattern)

應用場景
  • 事件通知
  • 狀態同步
  • 日志記錄
Spring事件機制
// Spring 觀察者模式
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {void onApplicationEvent(E event);
}// 具體實現
@Component
public class UserEventListener implements ApplicationListener<UserCreatedEvent> {@Overridepublic void onApplicationEvent(UserCreatedEvent event) {// 處理用戶創建事件System.out.println("User created: " + event.getUser());}
}

8. 狀態模式(State Pattern)

應用場景
  • 狀態機
  • 工作流
  • 訂單狀態
Spring狀態機
// Spring Statemachine 狀態模式
public interface StateMachine<S, E> {State<S, E> getState();void sendEvent(E event);void start();void stop();
}// 具體實現
@Configuration
@EnableStateMachine
public class OrderStateMachineConfig extends StateMachineConfigurerAdapter<OrderState, OrderEvent> {@Overridepublic void configure(StateMachineStateConfigurer<OrderState, OrderEvent> states) throws Exception {states.withStates().initial(OrderState.CREATED).state(OrderState.PAID).state(OrderState.SHIPPED).end(OrderState.DELIVERED);}
}

9. 策略模式(Strategy Pattern)

應用場景
  • 算法選擇
  • 支付方式
  • 緩存策略
Spring緩存策略
// Spring 緩存策略
public interface CacheManager {Cache getCache(String name);Collection<String> getCacheNames();
}// Redis緩存策略
public class RedisCacheManager implements CacheManager {@Overridepublic Cache getCache(String name) {return new RedisCache(name, redisTemplate);}
}// EhCache緩存策略
public class EhCacheCacheManager implements CacheManager {@Overridepublic Cache getCache(String name) {return new EhCacheCache(name, ehcache);}
}

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

應用場景
  • 算法框架
  • 流程控制
  • 代碼復用
Spring JdbcTemplate
// Spring JdbcTemplate 模板方法
public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {@Overridepublic <T> T queryForObject(String sql, Class<T> requiredType, Object... args) throws DataAccessException {return queryForObject(sql, args, requiredType);}@Overridepublic <T> T queryForObject(String sql, Object[] args, Class<T> requiredType) throws DataAccessException {List<T> results = queryForList(sql, args, requiredType);return DataAccessUtils.singleResult(results);}// 模板方法,子類可以重寫protected <T> List<T> queryForList(String sql, Object[] args, Class<T> elementType) throws DataAccessException {return query(sql, args, getSingleColumnRowMapper(elementType));}
}

11. 訪問者模式(Visitor Pattern)

應用場景
  • 數據結構操作
  • 編譯優化
  • 代碼生成
Spring Bean訪問者
// Spring Bean訪問者
public interface BeanDefinitionVisitor {void visitBeanDefinition(BeanDefinition beanDefinition);
}// 具體實現
public class BeanDefinitionVisitorImpl implements BeanDefinitionVisitor {@Overridepublic void visitBeanDefinition(BeanDefinition beanDefinition) {// 訪問Bean定義String beanClassName = beanDefinition.getBeanClassName();// 處理邏輯}
}

四、設計原則在Java后端開發中的應用

1. 單一職責原則(SRP)

// 好的設計:職責分離
@Service
public class UserService {public User createUser(UserDTO userDTO) {// 只負責用戶創建邏輯}
}@Service
public class EmailService {public void sendWelcomeEmail(User user) {// 只負責郵件發送邏輯}
}

2. 開閉原則(OCP)

// 通過接口擴展,對修改關閉
public interface PaymentStrategy {void pay(BigDecimal amount);
}@Component
public class AlipayStrategy implements PaymentStrategy {@Overridepublic void pay(BigDecimal amount) {// 支付寶支付邏輯}
}@Component
public class WechatPayStrategy implements PaymentStrategy {@Overridepublic void pay(BigDecimal amount) {// 微信支付邏輯}
}

3. 里氏替換原則(LSP)

// 子類可以替換父類
public interface Cache {void put(String key, Object value);Object get(String key);
}public class RedisCache implements Cache {@Overridepublic void put(String key, Object value) {// Redis實現}@Overridepublic Object get(String key) {// Redis實現}
}public class EhCache implements Cache {@Overridepublic void put(String key, Object value) {// EhCache實現}@Overridepublic Object get(String key) {// EhCache實現}
}

4. 接口隔離原則(ISP)

// 接口分離,避免胖接口
public interface UserReader {User findById(Long id);List<User> findAll();
}public interface UserWriter {User save(User user);void delete(Long id);
}public interface UserService extends UserReader, UserWriter {// 組合多個小接口
}

5. 依賴倒置原則(DIP)

// 依賴抽象而不是具體實現
@Service
public class OrderService {private final PaymentStrategy paymentStrategy;public OrderService(PaymentStrategy paymentStrategy) {this.paymentStrategy = paymentStrategy;}public void processOrder(Order order) {paymentStrategy.pay(order.getAmount());}
}

6. 迪米特法則(LoD)

// 減少對象間的耦合
@Service
public class OrderService {private final UserService userService;public void createOrder(OrderDTO orderDTO) {// 不直接訪問User的內部屬性User user = userService.getUserById(orderDTO.getUserId());// 通過User的方法獲取需要的信息if (user.canCreateOrder()) {// 創建訂單邏輯}}
}

7. 合成復用原則(CRP)

// 優先使用組合而不是繼承
@Service
public class OrderService {private final UserService userService;private final ProductService productService;private final PaymentService paymentService;// 通過組合復用功能,而不是繼承public Order createOrder(OrderDTO orderDTO) {User user = userService.getUserById(orderDTO.getUserId());Product product = productService.getProductById(orderDTO.getProductId());// 創建訂單邏輯return order;}
}

五、設計模式的最佳實踐

1. 模式選擇原則

  • 優先使用組合而非繼承
  • 針對接口編程而非實現
  • 遵循開閉原則
  • 保持簡單性

2. 常見反模式

  • 過度設計:不要為了使用模式而使用模式
  • 模式濫用:避免在不合適的地方使用設計模式
  • 忽略性能:某些模式可能帶來性能開銷

3. 性能考慮

// 單例模式的雙重檢查鎖定
public class Singleton {private static volatile Singleton instance;public static Singleton getInstance() {if (instance == null) {synchronized (Singleton.class) {if (instance == null) {instance = new Singleton();}}}return instance;}
}

4. 測試友好性

// 依賴注入便于測試
@Service
public class UserService {private final UserRepository userRepository;private final EmailService emailService;public UserService(UserRepository userRepository, EmailService emailService) {this.userRepository = userRepository;this.emailService = emailService;}// 方法便于單元測試public User createUser(UserDTO userDTO) {User user = new User(userDTO);user = userRepository.save(user);emailService.sendWelcomeEmail(user);return user;}
}

總結

設計模式是Java后端開發中的重要工具,它們幫助我們:

  1. 提高代碼質量:通過模式化的設計,代碼更加清晰、可維護
  2. 增強可擴展性:遵循開閉原則,便于功能擴展
  3. 提升開發效率:復用成熟的設計方案,避免重復造輪子
  4. 改善團隊協作:統一的代碼風格和架構模式

在實際開發中,應該根據具體場景選擇合適的模式,避免過度設計,同時注重性能和可測試性。通過深入理解Spring、MyBatis等主流框架的源碼,我們可以更好地掌握設計模式的實際應用。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/910576.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/910576.shtml
英文地址,請注明出處:http://en.pswp.cn/news/910576.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Python Arrow 庫詳解:更智能的日期時間處理

1. 安裝與基本用法 安裝 Arrow pip install arrow基本使用示例 import arrow# 獲取當前時間 now arrow.now() print(now) # 輸出: 2023-07-15T14:30:45.12345608:00# 創建特定時間 dt arrow.get(2023-07-15 14:30:00, YYYY-MM-DD HH:mm:ss) print(dt) # 輸出: 2023-07-15T…

大家電破渠道困局,小家電攻用戶體驗,云徙有何解法?

中國家電行業正經歷深刻轉型。 自2018年市場規模觸及8400億頂峰后&#xff0c;行業從增量競爭轉向存量博弈。與此同時&#xff0c;線上渠道在2023年首次以58%的占比超越線下&#xff0c;其中掃地機器人等小家電品類線上滲透率突破90%。消費需求也在同步重構——從家庭場景向個…

DMDPC多副本數據分布測試

需求&#xff1a;測試建表和插入數據是否會根據分布列進行自動分發。 驗證方法&#xff1a;1&#xff09;準備基礎環境&#xff1a;創建用戶和表空間。2&#xff09;創建數據分布測試表&#xff0c;并插入數據。3&#xff09;查詢指定分區數據&#xff0c;驗證數據分布情況。 …

Qt/C++開發監控GB28181系統/rtp解包/jrtplib庫的使用/同時支持udp和tcp被動和主動三種方式解包

一、前言說明 通過sip協議僅僅是交互&#xff0c;音視頻數據的收發最終并不是通過sip傳輸的&#xff0c;而是通過將數據打包成rtp的格式再通過udp或者tcp通信的&#xff0c;sip協議僅僅是告知對方待會要往哪里發數據&#xff0c;是udp還是tcp。由于數據都是rtp包格式&#xff…

集群聊天服務器---muduo庫的使用

使用 C 和 muduo 網絡庫來實現一個簡單的聊天服務器和客戶端。 服務器端&#xff1a; class chatServer { public:// 初始化TcpServerchatServer(muduo::net::EventLoop *loop,const muduo::net::InetAddress &listenAddr): _server(loop, listenAddr, "chatServer&…

關于Net Core Web API 項目測試 數據庫模擬的兩種不同方法 DC_week 6

1.關系型數據庫 插件&#xff1a;Microsoft.EntityFrameworkCore.InMemory Microsoft.EntityFrameworkCore.InMemory 是一個用于測試的“臨時內存數據庫”&#xff0c;讓你在不連接真實數據庫的情況下&#xff0c;測試 EF Core 的功能。 使用時就是用具體這個框架里面已經…

如何獲取 vscode 的 vsix 離線插件安裝包

1、搜索所需要的插件 Extensions for Visual Studio family of products | Visual Studio Marketplace網址 2、點擊 Repository 跳轉到對應的 git 倉庫 3、在 git 倉庫依次選擇 main , Tags, View all tags 4、選擇你想下載的版本&#xff0c;并點擊 downloads 5、往下滑動&…

ULS23 挑戰:用于計算機斷層掃描中 3D 通用病變分割的基準模型及基準數據集|文獻速遞-深度學習醫療AI最新文獻

Title 題目 The ULS23 challenge: A baseline model and benchmark dataset for 3D universal lesion segmentation in computed tomography ULS23 挑戰&#xff1a;用于計算機斷層掃描中 3D 通用病變分割的基準模型及基準數據集 01 文獻速遞介紹 每年進行的CT檢查數量持續…

WebSocket 端點 vs Spring Bean

在websocket端點中注入業務service時&#xff0c;不能像普通的springbean一樣通過Autowired或Resource注解進行注入。主要原因是websocket端點與spring容器中的bean的生命周期管理容器不同。 WebSocket 端點&#xff08;ServerEndpoint&#xff09;和 Spring Bean 的生命周期存…

MySQL8:jdbc插入數據后獲取自增ID

pom文件&#xff1a; <project xmlns"http://maven.apache.org/POM/4.0.0" xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"&…

MyBatis(Web后端開發第二期)

p.s.這是萌新自己自學總結的筆記&#xff0c;如果想學習得更透徹的話還是請去看大佬的講解 目錄 JDBC、數據庫連接池、lombok日志輸出SQL注入數據封裝XML映射文件動態SQL<if><where><set><foreach><sql><include> 配置文件 Mybatis是是一…

Angular1--Hello

最近有個小錯誤&#xff0c;因為最近還是在看thingsboard&#xff0c;最近終于看到前端的代碼&#xff0c;突然發現怎么全是ts的文件&#xff0c;仔細一看原來并不是之前認為的AngularJS&#xff0c;而是Angular。。。我tm真的無語了&#xff0c;又要去重新學。。。 Angular的…

什么是redission看門狗機制

Redisson 的看門狗機制(Watchdog Mechanism)是其實現可重入分布式鎖時的一個核心特性,主要用于解決業務邏輯執行時間超過鎖的過期時間(leaseTime)而導致鎖提前釋放,進而引發數據不一致的問題。它是一個自動的鎖續期機制。 ?? 核心問題:為什么需要看門狗? 分布式鎖的…

黑馬程序員蒼穹外賣DAY1

1. 前端頁面能正常顯示但無法登錄&#xff08;一直轉圈圈&#xff09; 找到下面路徑的dev.yml port一定要跟自己本機的保持一致&#xff0c;&#xff0c;username和password也一定是自己主機的用戶名和密碼&#xff0c;不然連不上。 登錄界面的密碼為數據庫表的密碼&#xff0…

Frida Hook Android App 點擊事件實戰指南:從進程識別到成功注入

一、背景與目標 在逆向分析和自動化測試中&#xff0c;Hook Android 的點擊事件是調試 UI 交互邏輯的重要手段之一。本文將以實際案例講解如何通過 Frida Hook public void onClick(View view) 方法&#xff0c;并解決常見的 Hook 失敗問題&#xff0c;最終實現對登錄按鈕的監…

Arduino Nano 33 BLE Sense Rev 2開發板使用指南之【環境搭建 / 點燈】

一、硬件介紹 1、產品特點 Arduino Nano 33 BLE Rev2&#xff0c;利用了nRF52840微控制器的先進功能。這款32位Arm Cortex-M4 CPU 64 MHz與MicroPython的兼容性增強了板子的靈活性&#xff0c;使其更容易被更廣泛的開發者社區所接受。 該開發板的突出特點是其藍牙低功耗&…

[QT]-宏使用

用宏,務必寫清文檔并用 do {…} while (0)為啥呢,示例 在 C/C++ 中,使用 do { … } while (0) 包裹宏定義是一種經典的最佳實踐,主要用于解決宏展開后的語法和邏輯問題。以下是詳細解釋和示例: 一、為什么用 do { … } while (0) 包裹宏? 避免分號導致的語法錯誤 問題場…

python-property、反射

# ### property """ 可以把方法變成屬性 : 可以動態的控制屬性的獲取,設置,刪除相關操作 property 獲取屬性 方法名.setter 設置屬性 方法名.deleter 刪除屬性 """ # 方法一 """是同一個方法名""" class MyCla…

【自動鼠標鍵盤控制器|支持圖像識別】

[軟件名稱]: 電腦圖像識別 [軟件大小]: 57.2 MB [下載通道]: 夸克盤 | 迅雷盤 &#x1f3ae;【自動鼠標鍵盤控制器&#xff5c;支持圖像識別】基于Python開發的智能自動化工具 輕量便捷的自動化操作工具&#xff0c;集成圖像識別、鼠標控制、鍵盤模擬等功能&#xff0c;輕松…

ISO/IEC 8824規范實際應用案例

案例 1&#xff1a;X.509 數字證書&#xff08;互聯網安全基石&#xff09; 標準依據&#xff1a;RFC 5280 (基于 ASN.1 定義) 核心應用&#xff1a; Certificate :: SEQUENCE {tbsCertificate TBSCertificate, -- 證書主體signatureAlgorithm AlgorithmIdentifier,…