网站外包,根据不同的用户来提供它们需要的网站
WebSite设计实现
public interface WebSite {
//网站调用方法,即享元角色的使用
public void use(User user);
}
ConcreteWebSite实现
public class ConcreteWebSite implements WebSite{
//网站发布的形式,享元角色的内部状态
private String type = "";
public ConcreteWebSite(String type) {
this.type = type;
}
@Override
public void use(User user) {
System.out.println("网站以【"+type+"】的形式使用中...【使用者:"+user.getName()+"】");
}
}
WebSiteFactory工厂实现
public class WebSiteFactory {
//模拟一个池
private HashMap<String, WebSite> pool = new HashMap<>();
//从池中取出享元角色,没有则创建放入
public WebSite getWebSite(String type) {
if(!pool.containsKey(type)) {
pool.put(type, new ConcreteWebSite(type));
}
return pool.get(type);
}
}
调用时附加上外部状态
public class Client {
public static void main(String[] args) {
//创建享元工厂
WebSiteFactory factory = new WebSiteFactory();
//获取享元角色
WebSite webSite1 = factory.getWebSite("新闻");
//使用附加上外部信息
webSite1.use(new User("Tom"));
//获取不存在的,直接创建
WebSite webSite2 = factory.getWebSite("博客");
//外部信息
webSite2.use(new User("Lin"));
}
}
Integer的Integer.valueOf()方法在-128~127的范围中使用的是享元模式
首先看到该方法,该方法的调用了享元工厂对象,他将得到的int值获取,判断是否符合池中共享对象的范畴,有则返回,没有则新建一个返回
public static Integer valueOf(int i) {
//可以发现,在IntegerCache中有对共享资源的一个限制
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
IntegerCache对象充当了一个享元工厂,可以发现最小值为-128,最大值为127,只有在这个范围内才是享元模式管理的范畴
private static class IntegerCache {
static final int low = -128;
static final int high;
//真正储存Integer对象的容器--池
static final Integer cache[];
//静态代码块初始化参数
static {
int h = 127;
String integerCacheHighPropValue =
sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
if (integerCacheHighPropValue != null) {
try {
int i = parseInt(integerCacheHighPropValue);
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;
//往池中添加-128~127的Inter对象
cache = new Integer[(high - low) + 1];
int j = low;
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() {}
}
原文:https://www.cnblogs.com/JIATCODE/p/13200724.html