设计模式原来这么简单-享元模式

享元模式

参考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.总结

简单来说,享元模式就是一种重用对象的思想,但要注意被重用对象的行为和属性应该是固定的。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值