上例中,具体的享元我们一共创建了4个,而我们输出的创建的对象个数是2个,这就是享元模式。可以减少对象创建的个数。
刚刚的例子,因为具体享元对象仅以一个String作为成员,实现很方便。下面我们再讲一个实际的例子:我们要检查许多天气的数据,主要有天气情况和温度组成,但是天气和温度的组合实际上是很容易相同的,为了减少创建的对象数量,我们使用享元模式:
首先是抽象的天气接口:
//享元接口public intece IWeather { void printWeather();}
其次是天气的实现。注意!这里我们使用HashMap来持有享元的引用,以为天气由具体天气情况和温度共同确定他们是否相同,我们需要使用两个做key,但key只能是一个对象,所以最终我们选择这个对象来当key。HashMap的Key是有限制的,必须正确提供hashCode()方法(HashMap以这个为基础存取数据的)和equals()方法(HashMap通过key取时判断Key是否相等会调用Key的这个方法)。下面的实现中就实现了这两个方法:
//具体享元public class Weather implements IWeather{ private String weather; private Integer temperature; public Weather(String weather,int temperature){ this.weather = weather; this.temperature = temperature; } @Override public void printWeather() { System.out.print("天气:" weather); System.out.println(" 温度:" temperature); } @Override public boolean equals(Object obj) {//两个同时相等这个对象才相同 Weather weather = (Weather)obj; return weather.weather.equals(this.weather)&&weather.temperature==temperature; } @Override public int hashCode() {//Integer和String的hashCode()方法都是很合理的,这里取均即可 return (weather.hashCode()temperature.hashCode())/2; }}
接下来就是享元工厂,为我们产生具体天气的工厂类:
//享元工厂public class WeatherFactory { private HashMap<IWeather, IWeather> weathers; public WeatherFactory(){ weathers = new HashMap<IWeather, IWeather>(); } public IWeather getFlyWeight(String weather,int temperature){ Weather objectWeather = new Weather(weather, temperature); IWeather flyweight = weathers.get(objectWeather); if(flyweight == null){ flyweight = objectWeather; weathers.put(objectWeather, flyweight); } else objectWeather = null;//方便gc回收 return flyweight; } public int getFlyweightSize(){ return weathers.size(); } }
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-33893-41.html
写得不好
包装前就有了呢
立刻就会跟风搞起一大堆