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());
              }
          }
      }
      
      ~~~
相关推荐
怪兽源码20 分钟前
基于SpringBoot的选课调查系统
java·spring boot·后端·选课调查系统
恒悦sunsite26 分钟前
Redis之配置只读账号
java·redis·bootstrap
梦里小白龙32 分钟前
java 通过Minio上传文件
java·开发语言
人道领域32 分钟前
javaWeb从入门到进阶(SpringBoot事务管理及AOP)
java·数据库·mysql
sheji52611 小时前
JSP基于信息安全的读书网站79f9s--程序+源码+数据库+调试部署+开发环境
java·开发语言·数据库·算法
毕设源码-邱学长1 小时前
【开题答辩全过程】以 基于Java Web的电子商务网站的用户行为分析与个性化推荐系统为例,包含答辩的问题和答案
java·开发语言
摇滚侠1 小时前
Java项目教程《尚庭公寓》java项目从开发到部署,技术储备,MybatisPlus、MybatisX
java·开发语言
€8111 小时前
Java入门级教程24——Vert.x的学习
java·开发语言·学习·thymeleaf·数据库操作·vert.x的路由处理机制·datadex实战
Mr_star_galaxy2 小时前
【JAVA】经典图书管理系统的实现
java
昊坤说不出的梦2 小时前
【实战】监控上下文切换及其优化方案
java·后端