Service设计模式

\*\*`面向用户操作`\*\*的功能代码封装,Service业务层封装了用户的操作功能,一个用户操作,对应Service的一个方法。

(一)**场景**

!\[\](image/image_5_2cr5ldrq.png)

(二)Service编程

**Service编码规范**

  • ① 一个业务模块(相关的功能属于一个模块,比如管理相关功能、账户相关操作等)的方法放在一个Service类中,命名:**`XxxxService`**,保持望文生义。

  • ② 用户的一个操作功能对应service一个方法,例如:`开卡`、`编辑卡号`、`注销卡号`、`转账`,对应方法 `openCard`、`editCard`、`removeCard`、`transfer`。

  • ③ Service的java类,通常放在`service`包下或者biz包下。

**示例代码:**

  • 转账功能:

  • 实体类:

~~~java

复制代码
  package com.xx.entity;
    
    import java.io.Serializable;
    //映射t_account表
    public class Account implements Serializable {
        private Integer accountId;
        private String username;
        private String password;
        private Double balance;
        //省略getter、setter、构造
    }
    ~~~
  • DAO:

    java 复制代码
        package com.xx.dao;
        
        import com.xx.entity.Account;
        
        public interface AccountDao {
            /**
             * 根据账户名查询指定信息
             * @param username 被查询的账户名
             * @return 对应的对象信息
             */
            Account selectAccountByUsername(String username);
        
            /**
             * 根据账户名修改余额
             * @param username 被修改的账户名
             * @param newBalance 修改后的余额
             * @return 受影响的行数
             */
            int updateAccountByUsername(String username, double newBalance);
        }
        
        ~~~

~~~java

复制代码
 package com.xx.dao.impl;
    
    import com.xx.dao.AccountDao;
    import com.xx.entity.Account;
    import com.xx.util.JDBCUtils;
    import org.springframework.jdbc.core.BeanPropertyRowMapper;
    import org.springframework.jdbc.core.JdbcTemplate;
    
    import java.util.List;
    
    public class AccountDaoImpl implements AccountDao {
        private JdbcTemplate jdbcTemplate = JDBCUtils.getJDBCTemplate();
    
        @Override
        public Account selectAccountByUsername(String username) {
            String sql = "select * from t_account where username=?";
            List<Account> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Account.class), username);
            return list.isEmpty() ? null : list.get(0);
        }
    
        @Override
        public int updateAccountByUsername(String username, double newBalance) {
            String sql = "update t_account set balance=? where username=?";
            return jdbcTemplate.update(sql, newBalance, username);
        }
    }
    
    ~~~
  • Service:

    复制代码
    ~~~java
      package com.xx.service;
      
      public interface AccountService {
          /**
           * 转账功能
           * @param fromName 用户输入的转出人姓名
           * @param toName 用户输入的转入人姓名
           * @param money 转账金额
           * @return转账是否成功的结果
           */
          boolean transfer(String fromName,String toName,double money);
      }
      ~~~

~~~java

复制代码
  package com.xx.service.impl;
    
    import com.xx.dao.AccountDao;
    import com.xx.dao.impl.AccountDaoImpl;
    import com.xx.entity.Account;
    import com.xx.service.AccountService;
    
    public class AccountServiceImpl implements AccountService {
        private AccountDao ad = new AccountDaoImpl();
        @Override
        public boolean transfer(String fromName, String toName, double money) {
            //判断转出人是否存在
            Account from = ad.selectAccountByUsername(fromName);
            if (from == null) {
                throw new RuntimeException("转出人不存在!");
            }
            //判断余额是否充足
            if (from.getBalance() < money) {
                throw new RuntimeException("余额不足!");
            }
            //判断转入人是否存在
            Account to = ad.selectAccountByUsername(toName);
            if (to == null) {
                throw new RuntimeException("转入人不存在!");
            }
            //执行转账
            int n = ad.updateAccountByUsername(fromName, from.getBalance() - money);
            n += ad.updateAccountByUsername(toName, to.getBalance() + money);
            if (n == 2) {
                return true;
            }
    
            return false;
    
    
    
        }
    }
    ~~~
  • 视图层:

    复制代码
    ~~~java
      package com.xx.view;
      
      import com.xx.service.AccountService;
      import com.xx.service.impl.AccountServiceImpl;
      
      import java.util.Scanner;
      
      public class TransferView {
          public static void main(String[] args) {
              Scanner sc = new Scanner(System.in);
              System.out.println("请输入转出人的账户名:");
              String fromName = sc.next();
              System.out.println("请输入转账金额:");
              double money = sc.nextDouble();
              System.out.println("请输入转入人的账户名:");
              String toName = sc.next();
      
              //调用转账功能
              AccountService as = new AccountServiceImpl();
      
              try {
                  if (as.transfer(fromName, toName, money)) {
                      System.out.println("转账成功!");
                  } else {
                      System.out.println("转账失败");
                  }
              } catch (Exception e) {
                  System.out.println("转账失败!详细信息为:"+e.getMessage());
              }
          }
      }
      
      ~~~
相关推荐
星落梦生5 小时前
SpringAOP基础笔记(7)
java·开发语言
金銀銅鐵6 小时前
带您看懂字节码指令(四):一条指令里有什么
java·jvm
最强小杰6 小时前
某 OpenAI 兼容网关上的 `kimi-k3.1-pro`:Cline、Zed 接入与 SSE 排错示例
java·服务器·网络·ai
Flynn Liang6 小时前
流量治理不是限流那么简单:I/O 密集型 Java 服务的 6 层防线
java·微服务·高并发·限流·熔断·系统稳定性·resilience4j
学长毕设7 小时前
基于SpringBoot智慧养老服务平台设计与实现-附源码
java·spring boot·后端
曹牧7 小时前
Java:“刷新雪崩”
java·开发语言
秋天的怀念_David7 小时前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
Forget the Dream9 小时前
Spring AI 2.0 系列(二):第一个 ChatClient——从注入到一次完整调用
java·人工智能·spring boot·ai·springai
黑十10 小时前
FDE 怎么快速搭一个可演示页面?最小前端方案
java·大数据·前端·数据库·人工智能
神明不懂浪漫11 小时前
【第八章】多线程(一)
java·开发语言·经验分享·笔记