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());
              }
          }
      }
      
      ~~~
相关推荐
顾北121 小时前
MCP服务端开发:图片搜索助力旅游计划
java·spring boot·dubbo
我命由我123452 小时前
Android 广播 - 静态注册与动态注册对广播接收器实例创建的影响
android·java·开发语言·java-ee·android studio·android-studio·android runtime
赛姐在努力.2 小时前
【拓扑排序】-- 算法原理讲解,及实现拓扑排序,附赠热门例题
java·算法·图论
yxc_inspire2 小时前
Java学习第二天
java·面向对象
毕设源码-赖学姐2 小时前
【开题答辩全过程】以 基于net超市销售管理系统为例,包含答辩的问题和答案
java
昀贝2 小时前
IDEA启动SpringBoot项目时报错:命令行过长
java·spring boot·intellij-idea
roman_日积跬步-终至千里2 小时前
【LangGraph4j】LangGraph4j 核心概念与图编排原理
java·服务器·数据库
野犬寒鸦3 小时前
从零起步学习并发编程 || 第六章:ReentrantLock与synchronized 的辨析及运用
java·服务器·数据库·后端·学习·算法
wenzhangli73 小时前
ooderA2UI BridgeCode 深度解析:从设计原理到 Trae Solo Skill 实践
java·开发语言·人工智能·开源
HalvmånEver3 小时前
Linux:线程互斥
java·linux·运维