- 代码的重构
- 1. 代码的重构
- 2. 创建牌相关工具类
- 3. 创建图层相关工具类
- 4. 修改LayerUtil.java
代码的重构
学习于bilibili 春娇与志明
1. 代码的重构
将之前的代码进行封装和重构
方便之后的阅读和维护
故将代码封装,对外提供一个统一访问的入口
2. 创建牌相关工具类
在utill包中创建BrandUtil.java类
package com.zy.utill;/*
工具类
提供创建牌相关的一些公共算法*/import com.zy.model.Brand;import java.util.Random;//随机获取牌名称
public class BrandUtil {public static Random random = new Random();//存储所有牌的名称public static String [] brandNames = {"刷子","剪刀","叉子","手套","水桶","火","玉米","球","瓶子","白菜","稻草","肉腿","胡萝卜","苹果","铃铛","青草"};//每次调用都随机获取一个牌的名称public static String getBrandName(){int randomIndex = random.nextInt(brandNames.length);return brandNames[randomIndex];}//创建随机牌的数组时public Brand[] buildBrands(Integer capacity){Brand[] brands = new Brand[capacity];//数组容量等于图层容量//遍历循环//每次产生3张,保证可以消除//容量为3的倍数for (int i = 0; i < brands.length; i = i + 3) {String randonBrandName = getBrandName();//每次循环获取牌的名称Brand brand1 = new Brand(randonBrandName);Brand brand2 = new Brand(randonBrandName);Brand brand3 = new Brand(randonBrandName);brands[i] = brand1;brands[i+1] = brand2;brands[i+2] = brand3;}for (int i = 0; i < brands.length; i++) {//当前位置A的变量拿到Brand brandA = brands[i];//交换位置Bint randomIndex = random.nextInt(brands.length);//获得0到长度大小的随机整数Brand brandB = brands[randomIndex];//交换Brand temp = brandA;brands[i] = brandB;brands[randomIndex] = temp;}return brands;}}
3. 创建图层相关工具类
在utill包中创建LayerUtil.java类
package com.zy.util;import com.zy.model.Brand;
import com.zy.model.Cell;
import com.zy.model.Layer;public class LayerUtil {public static Layer build(Integer rowNum,Integer colNum){Layer layer = null;//容量为36的二维数组图层try {layer = new Layer(rowNum,colNum);} catch (Exception e) {throw new RuntimeException(e);}Brand[] brands = BrandUtil.buildBrands(layer.getCapacity());//数组容量等于图层容量int flag = 0;Cell[][] cells = layer.getCells();for (int row = 0; row < cells.length; row++) {for (int col = 0; col < cells[row].length; col++) {// System.out.println(row + "-" + col);Cell cell = new Cell();cell.setState(1);cell.setBrand(brands[flag++]);cells[row][col] = cell;//把之前空的图层设置了值}}// layer.showCells();return layer;}
}
4. 修改LayerUtil.java
在LayerUtil.java中添加
public void showCells(){for (int row = 0; row < cells.length; row++) {for (int col = 0; col < cells[row].length; col++) {Brand brands1 = cells[row][col].getBrand();System.out.print(brands1.getName() + " ");}System.out.println();}}