FlyWeight : 是抽象等享元角色,他是产品等抽象类,同时定义出对象等外部状态和内部状态
ConcreteFlyWeight : 是具体的享元角色,是具体的产品类,实现抽象角色定义相关业务
UnshareaConcreteFlyWeight : 是不可共享角色
FlyWeightFactory : 享元工厂类,用于构建一个池容器,同时提供获取方法
小型等外包项目,给客户A做一个产品展示网站,客户A等朋友感觉不错,希望做这样等产品展示网站,但要求不同
新建WebSite类
public abstract class WebSite {
public abstract void use(); //抽象方法
}
新增实现类
public class ConcreteWebSite extends WebSite{
private String type = "";
public ConcreteWebSite(String type) {
this.type = type;
}
@Override
public void use() {
System.out.println("网站发布形式为 :" + type);
}
}
新增享元工厂类 (池的概念)
public class WebSiteFactory {
/**
* 池
*/
private HashMap<String,ConcreteWebSite> pool = new HashMap<>();
/**
* 根据类型,返回一个网站,如果没有就创建,并且放入到池中
*/
public WebSite getWebSiteCategory(String type){
if(!pool.containsKey(type)){
pool.put(type,new ConcreteWebSite(type));
}
return (WebSite)pool.get(type);
}
/**
* 获取池中网站分类总数
*/
public int getWebSiteCount(){
return pool.size();
}
}
客户端
public class Client {
public static void main(String[] args) {
//创建工厂类
WebSiteFactory webSiteFactory = new WebSiteFactory();
//客户要分布新闻
WebSite webSite = webSiteFactory.getWebSiteCategory("新闻");
webSite.use();
//客户要分布新闻
WebSite webSite2 = webSiteFactory.getWebSiteCategory("博客");
webSite2.use();
}
}
public final class Integer extends Number implements Comparable<Integer> {
/**
* A constant holding the minimum value an {@code int} can
* have, -231.
*/
@Native public static final int MIN_VALUE = 0x80000000;
/**
* A constant holding the maximum value an {@code int} can
* have, 231-1.
*/
@Native public static final int MAX_VALUE = 0x7fffffff;
……
}
// 在一个区间之内,直接用IntegerCache.cache[]数组里面的数返回,否则new 一个新对象。
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
private static class IntegerCache {
static final int low = -128; //Integer的最低值
static final int high; //最高值
static final Integer cache[]; //缓存数组
static {
// high value may be configured by property
int h = 127;
这里可以在运行时设置虚拟机参数来确定
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
//不能小于127
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
//不能超过最大值
h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
} catch( NumberFormatException nfe) {
// If the property cannot be parsed into an int, ignore it.
}
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
//循环将区间的数赋值给cache[]数组
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
// range [-128, 127] must be interned (JLS7 5.1.7)
assert IntegerCache.high >= 127;
}
private IntegerCache() {
}
}
用一个Integer数组先缓存了,后面如果是是在区间内的数直接从缓存数组中取,否则才构造新的Integer
个人博客地址:http://blog.yanxiaolong.cn/