享元模式
参考https://github.com/iluwatar/java-design-patterns
1.什么是享元模式
WIKI:通过共享相同对象的尽可能多的数据来减少内存使用,当大量使用简单且可重用的对象(simple repeated representation)而使用了大量的内存时,该模式是解决该问题的最佳实践。
2.实例
在游戏的商店里会出售不同的药水,但是同一种药水药效是一样的,所以没必要为每一瓶药水都创建一个对象
public interface Potion {
/**
* 发挥药效
*/
void apply();
/**
* 获取价格
*/
double getPrice();
}
public class BluePotion implements Potion {
private double price;
public BluePotion(){
System.out.println("创建了蓝药水");
}
public BluePotion(double price) {
this.price = price;
}
@Override
public void apply() {
System.out.println("使用一瓶蓝药水...");
}
@Override
public double getPrice() {
return price;
}
}
public class RedPotion implements Potion {
private double price;
public RedPotion(){
System.out.println("创建了红药水");
}
public RedPotion(double price){
this.price = price;
}
@Override
public void apply() {
System.out.println("使用一瓶红药水...");
}
@Override
public double getPrice() {
return price;
}
}
public class PotionFactory {
private static final Map<Class<?>, Potion> SharingObjs = new HashMap<>();;
public static Potion getInstance(Class<?> clazz) {
Potion potion = null;
try {
potion = createPotions(clazz);
} catch (IllegalAccessException | InstantiationException e) {
e.printStackTrace();
}
return potion;
}
private static Potion createPotions(Class<?> clazz) throws IllegalAccessException, InstantiationException {
if(!verifyClazz(clazz)){
throw new IllegalArgumentException("不合法的参数!");
}
if(SharingObjs.containsKey(clazz)){
return SharingObjs.get(clazz);
}
Potion potion = (Potion) clazz.newInstance();
SharingObjs.put(clazz, potion);
return potion;
}
private static boolean verifyClazz(Class<?> clazz) {
Class<?>[] interfaces = clazz.getInterfaces();
for (Class<?> anInterface : interfaces) {
if(anInterface == Potion.class){
return true;
}
}
return false;
}
}
@Test
public void test() {
Potion red1 = PotionFactory.getInstance(RedPotion.class);
Potion red2 = PotionFactory.getInstance(RedPotion.class);
Potion blue1 = PotionFactory.getInstance(BluePotion.class);
Potion blue2 = PotionFactory.getInstance(BluePotion.class);
red1.apply();
red2.apply();
blue1.apply();
blue2.apply();
}
创建了红药水
创建了蓝药水
使用一瓶红药水…
使用一瓶红药水…
使用一瓶蓝药水…
使用一瓶蓝药水…
3.总结
简单来说,享元模式就是一种重用对象的思想,但要注意被重用对象的行为和属性应该是固定的。