如果在一个系统中存在多个相同的对象,那么只需要共享一份对象的拷贝,而不必为每一次使用都创建新的对象。目的是提高系统性能。
享元模式(Flyweight),运行共享技术有效地支持大量细粒度的对象,避免大量拥有相同内容的小类的开销(如耗费内存),使大家共享一个类(元类)。
下面是Java中自带的一种享元模式:
public class TestString {
public static void main(String[] args) {
String s1 = "abc";
String s2 = "abc";
String s3 = new String("abc");
String s4 = new String("abc");
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
System.out.println(s3 == s4); // false
System.out.println(s3.intern() == s1); // true
System.out.println(s3.intern() == s4.intern()); // true
}
}
下面是另一个例子
建筑接口:Building
public interface Building {
void use();
}
体育馆实现类:Gym
public class Gym implements Building {
private String name;
private String shape;
private String sport;
public Gym(String sport) {
this.setSport(sport);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getShape() {
return shape;
}
public void setShape(String shape) {
this.shape = shape;
}
public String getSport() {
return sport;
}
public void setSport(String sport) {
this.sport = sport;
}
@Override
public void use() {
System.out.println("该体育馆被使用来召开奥运会" + " 运动项目为:" + sport + " 形状为:" + shape + " 名称为:" + name);
}
}
建筑工厂类:GymFactory
import java.util.*;
public class GymFactory {
private static final Map<String, Gym> gymMap = new HashMap<>();
public static Gym getGym(String sport) {
Gym gym = gymMap.get(sport);
if (gym == null) {
gym = new Gym(sport);
gymMap.put(sport, gym);
}
return gym;
}
public static int getSize() {
return gymMap.size();
}
}
测试类:Client
public class Client {
public static void main(String[] args) {
String sport = "足球";
for (int i = 1; i <= 5; i++) {
Gym tyg = GymFactory.getGym(sport);
tyg.setName("中国体育馆");
tyg.setShape("圆形");
tyg.use();
System.out.println("对象池中对象数量为:" + GymFactory.getSize());
}
}
}
执行结果: