是结构型设计模式,其目的是为了减少大量的重复对象。
java中String就是享元模式的。看下例子
package com.pattern.struct.flyweight;
public class TestString {
public static void main(String[] args) {
String a = "abc";
String b = "abc";
System.out.println(a == b);
}
}
输出结果为true,说明a和b是存在同一个内存地址上的,也就是我们只创建了一个“abc”的字符串,a和b都指向这个字符串。
看下面享元模式的简单实现。
package com.pattern.struct.flyweight;
public interface Flyweight {
}
package com.pattern.struct.flyweight;
public class ConcreteFlyweight implements Flyweight {
private String inner = null;
public ConcreteFlyweight(String state){
this.inner = state;
}
}
package com.pattern.struct.flyweight;
import java.util.HashMap;
import java.util.Map;
public class FlyweightFactory {
private Map<String,Flyweight> cache = new HashMap<String,Flyweight>();
public Flyweight factory(String state){
Flyweight fly = cache.get(state);
if(fly == null){
fly = new ConcreteFlyweight(state);
cache.put(state, fly);
}
return fly;
}
}
package com.pattern.struct.flyweight;
public class Client {
public static void main(String[] args) {
FlyweightFactory factory = new FlyweightFactory();
Flyweight fly1 = factory.factory("a");
Flyweight fly2 = factory.factory("b");
Flyweight fly3 = factory.factory("a");
System.out.println(fly1 == fly2);
System.out.println(fly1 == fly3);
}
}
结果如下:
false
true