CellStyleFactory减少cellstyle的创建,提高利用率

  |   0 评论   |   0 浏览
package org.apache.myfaces.FactoryPattern;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.util.HashMap;
import java.util.Map;

public class CellStyleFactory {

    public Map<Integer, Map<String,CellStyle>> container = new HashMap<>();


    private CellStyleFactory() {
    }

    public CellStyle getInstance(String color, Workbook workbook){
        int hashCode = workbook.hashCode();
        if(!container.containsKey(hashCode)||(!container.get(hashCode).containsKey(color))){
            CellStyle cellStyle = workbook.createCellStyle();
            if (color.equalsIgnoreCase("RED")){
                cellStyle.setTopBorderColor((short)100);
            }else if (color.equalsIgnoreCase("BLUE")){
                cellStyle.setTopBorderColor((short)200);
            }
            container.put(hashCode,new HashMap(){
                {
                    put(color,cellStyle);
                }
            });
        }
        return container.get(hashCode).get(color);
    }

    /**
     * cellstyle中重写了equals和hashcode方法,如果index一样,那么为同一个对象
     * @param args
     */
    public static void main(String[] args) {
        CellStyleFactory cellStyleFactory = new CellStyleFactory();
        Workbook workbook1 = new HSSFWorkbook();
        Workbook workbook2 = new HSSFWorkbook();

        CellStyle cellStyle1 = workbook1.createCellStyle();
        CellStyle cellStyle2 = workbook2.createCellStyle();
        System.out.println("cellStyle1.getIndex():"+cellStyle1.getIndex());
        System.out.println("cellStyle2.getIndex():"+cellStyle2.getIndex());

        System.out.println("cellStyle1:"+cellStyle1.hashCode());
        System.out.println("cellStyle2:"+cellStyle2.hashCode());

        System.out.println("w1 hashcode:"+workbook1.hashCode());
        System.out.println("w2 hashcode:"+workbook2.hashCode());
        CellStyle w1_red = cellStyleFactory.getInstance("RED", workbook1);
        CellStyle w1_red_2 = cellStyleFactory.getInstance("BLUE", workbook1);

        CellStyle w2_red = cellStyleFactory.getInstance("RED", workbook2);
        CellStyle w2_red_2 = cellStyleFactory.getInstance("BLUE", workbook2);

        System.out.println(w1_red.hashCode()+"|============|"+w1_red_2.hashCode());
        System.out.println(w2_red.hashCode()+"|============|"+w2_red_2.hashCode());

    }


}


标题:CellStyleFactory减少cellstyle的创建,提高利用率
作者:MingGH
地址:https://runnable.run/articles/2020/03/04/1583303879486.html