享元模式

案例

1
2
3
4
小型的外包项目,给客户A做一个产品展示网站,客户A的朋友感觉效果不错,也希望做这样的产品展示网站,但是要求都有些不同
1)有客户要求以新闻的形式发布
2)有客户人要求以博客的形式发布
3)有客户希望以微信公众号的形式发布

传统方式的解决方法

直接复制粘贴一份,然后根据客户不同要求,进行定制修改给每个网站租用一个空间

问题

  1. 需要的网站结构相似度很高,而且都不是高访问量网站,如果分成多个虚拟空间来处理,相当于一个相同网站的实例对象很多,造成服务器的资源浪费
  2. 解决思路:整合到一个网站中,共享其相关的代码和数据,对于硬盘、内存、CPU、数据库空间等服务器资源都可以达成共享,减少服务器资源
  3. 对于代码来说,由于是一份实例,维护和扩展都更加容易
  4. 上面的解决思路就可以使用享元模式来解决

基本介绍

  1. 享元模式( Flyweight Pattern)也叫蝇量模式:运用共享技术有效地支持大量细粒度的对象
  2. 常用于系统底层开发,解决系统的性能问题。像数据库连接池,里面都是创建好的连接对象,在这些连接对象中有我们需要的则直接拿来用,避免重新创建,如果没有我们需要的,则创建一个
  3. 享元模式能够解决重复对象的内存浪费的问题,当系统中有大量相似对象,需要缓冲池时。不需总是创建新对象,可以从缓冲池里拿。这样可以降低系统内存,同时提高效率
    享元模式经典的应用场景就是池技术了,String常量池、数据库连接池、缓冲池等等都是享元模式的应用,享元模式是池技术的重要实现方式

![Flyweight Structure.png-72.6kB](享元模式/Flyweight Structure.png)

角色

  • flyweight: 享元接口,通过这个接口传入外部状态并作用于外部状态,定义内部状态

  • ConcreteFlyweight: 具体的享元实现对象,必须是可共享的,需要封装享元对象的内部状态;

  • UnsharedConcreteFlyweight: 非共享的享元实现对象,并不是所有的享元对象都可以共享,非共享的享元对象通常是享元对象的组合对象;一般不会用在享元工厂。

  • FlyweightFactory: 享元工厂,主要用来创建并管理共享的享元对象,并对外提供访问共享享元的接口

享元模式提出了两个要求:细粒度和共享对象这里就涉及到内部状态和外部状态了,即将对象的信息分为两个部分:内部状态和外部状态

  • 内部状态指对象共享出来的信息,存储在享元对象内部且不会随环境的改变而改变
  • 外部状态指对象得以依赖的一个标记,是随环境改变而改变的、不可共享的状态。

举个例子:围棋理论上有361个空位可以放棋子,每盘棋都有可能有两三百个棋子对象产生,因为内存空间有限,一台服务器很难支持更多的玩家玩围棋游戏,如果用享元模式来处理棋子,那么棋子对象就可以减少到只有两个实例,这样就很好的解决了对象的开销问题

解决问题

  1. flyweight
1
2
3
public abstract class WebSite {
public abstract void use();
}
  1. ConcreteFlyweight
1
2
3
4
5
6
7
8
9
10
11
12
13
public class ConcreteWebSite extends WebSite {

private String type = ""; //网站发布形式

public ConcreteWebSite(String type) {
this.type = type;
}

@Override
public void use() {
System.out.println("网站发布形式为:" + type);
}
}
  1. FlyweightFactory
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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 pool.get(type);
}

//获取网站分类的总是
public int getWebSiteCount(){
return pool.size();
}

}
  1. client
1
2
3
4
5
6
7
8
9
10
11
public class Client {

public static void main(String[] args) {
WebSiteFactory webSiteFactory = new WebSiteFactory();

WebSite webSite1 = webSiteFactory.getWebSiteCategory("新闻");
webSite1.use();
WebSite webSite2 = webSiteFactory.getWebSiteCategory("博客");
webSite2.use();
}
}

添加外部状态

1
2
3
4
5
6
7
8
9
10
11
12
13
public class User {

private String name;

public String getName() {
return name;
}

public User setName(String name) {
this.name = name;
return null;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public abstract class WebSite {
public abstract void use(User user);
}

public class ConcreteWebSite extends WebSite {

private String type = ""; //网站发布形式

public ConcreteWebSite(String type) {
this.type = type;
}

@Override
public void use(User user) {
System.out.println("网站发布形式为:" + type + ", 使用者:" + user.getName());
}
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Client {

public static void main(String[] args) {
WebSiteFactory webSiteFactory = new WebSiteFactory();

WebSite webSite1 = webSiteFactory.getWebSiteCategory("新闻");
User user1 = new User();
user1.setName("aaa");
webSite1.use(user1);
WebSite webSite2 = webSiteFactory.getWebSiteCategory("新闻");
User user2 = new User();
user2.setName("bbb");
webSite2.use(user2);
}
}

在JDK中的使用

Integer类就使用了享元模式

1
2
3
4
5
6
7
8
9
10
11
12
13
public class FlyWeight {
public static void main(String[] args) {
Integer x = Integer.valueOf(127);
Integer y = new Integer(127);
Integer z = Integer.valueOf(127);
Integer w = new Integer(127);
System.out.println(x.equals(y)); //true
System.out.println(x == y); //false
System.out.println(x == z); //true
System.out.println(w == x); //false
System.out.println(w == y); //false
}
}

valueOf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
//在 -128 -- 127使用享元模式
private static class IntegerCache {
static final int low = -128;
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);
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;
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() {}
}
  1. 在valueOf方法中,先判断值是否在IntegerCache 中,如果不在,就创建新的Integer对象
  2. value0F 方法,就使用到享元模式
  3. 如果使用valueOf方法得到一个Integer实例,范围在-128 - 127,执行速度比 new 快

注意事项

  • 在享元模式这样理解,“享”就表示共享,“元”表示对象
  • 系统中有大量对象,这些对象消耗大量内存,并且对象的状态大部分可以外部化时,我们就可以考虑选用享元模式
  • 用唯一标识码判断,如果在内存中有,则返回这个唯一标识码所标识的对象,用HashMap/HashTable存储
  • 享元模式大大减少了对象的创建,降低了程序内存的占用,提高效率
  • 享元模式提高了系统的复杂度。需要分离出内部状态和外部状态,而外部状态具有固化特性,不应该随着内部状态的改变而改变,这是我们使用享元模式需要注意的地方.
  • 使用享元模式时,注意划分内部状态和外部状态,并且需要有一个工厂类加以控制
  • 经典的应用场景是需要缓冲池的场景,比如 String常量池、数据库连接池