EXCEL单元格的获取——多例模式

       因为Excel的单元格的行列与单元格是一一相应的,行与列组成的是一对联合主键。给定一个单元格行列或者给定一个单元格名称。须要找到相应的单元格;这样就形成了一种映射关系。须要使用单例模式的变式——多例模式,进行实现。

       多例模式的核心是用一个HashMap<K,V>来实现这样的映射关系。V明显是目标单元格。K必须保存单元格的行与列一一相应信息,能够用单元格名称来表示;实现代码例如以下:

import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author lcx
 *
 */
public class CellMap {

	private static HashMap<String,CellMap> map=new HashMap();

	private CellMap(String cellName)
	{
		System.out.println("新建一个:"+cellName);
		map.put(cellName, this);
	}

	public static CellMap getInstance(int row,int col)
	{
		return getInstance( cellName(row,col));
	}

	public static CellMap getInstance(String cellName)
	{
		if(map.get(cellName)!=null)
			return map.get(cellName);
		else
			return new CellMap(cellName);
	}

	private static String cellName(int row,int col)
	{
		ArrayList<Character> list=new ArrayList();
		while(col>0)
		{
			list.add((char) (col%26+'A'-1));
			col/=26;
		}
		StringBuffer buffer=new StringBuffer();
		for(int i=list.size()-1;i>=0;i--)
			buffer.append(list.get(i));
		buffer.append(""+row);
		return buffer.toString();
	}

	public static void main(String[] args) {
		//首次获取
		for(int i=1;i<10;i++)
			for(int j=1;j<10;j++)
			{
				CellMap.getInstance(i, j);
			}
		//再次获取
		for(int i=1;i<10;i++)
			for(int j=1;j<10;j++)
			{
				CellMap.getInstance(i, j);
			}
	}

}


原文地址:https://www.cnblogs.com/gavanwanggw/p/6842618.html