享元模式听名字就知道是共享一个东西,为了节省内存嘛。那么它和单例模式有什么不同呢?单例模式就一个对象,而享元模式是一组对象,共享的是相同的对象。没错,我们的String就用的享元模式,下面我们代码实现:
public class Flyweight {
interface 字符串 {
void operation();
}
public static class 包装字符串 implements 字符串 {//可以有斜体字符串,但重点不是这
private String string;
public 包装字符串(String str) {
string = str;
}
public void operation() {
System.out.println(this.hashCode());
}
}
public static class FlyweightFactory { //这里看出工厂模式的好处了吧
private Hashtable<String, 字符串> flyweights = new Hashtable<>();
public FlyweightFactory() {
}
public 字符串 getFlyWeight(String obj) {
字符串 flyweight = flyweights.get(obj);
if (flyweight == null) {//不同的String才产生新的对象
flyweight = new 包装字符串(obj);
flyweights.put(obj, flyweight);
}
return flyweight;
}
}
public static void main(String[] args) {
FlyweightFactory factory = new FlyweightFactory();
字符串 fly1 = factory.getFlyWeight("Google");
字符串 fly2 = factory.getFlyWeight("Qutr");
字符串 fly3 = factory.getFlyWeight("Google");
fly1.operation();
fly2.operation();
fly3.operation();
}
}
输出:
2133927002
1836019240
2133927002
觉得容易理解的话面向对象的23种设计模式点这里