(结构型模式)享元模式---羊了个🐑

160 阅读2分钟

🐑简介

运用共享技术来有效地支持大量细粒度对象的重用,通过共享已经存在的对象来大幅度减少需要创建的对象数量,避免大量相似对象的开销,从而提高系统资源的利用率

🐑角色

  • 抽象享元角色(Flyweight):是所有的具体享元类的基类,为具体享元规范需要实现的公共接口,非享元的外部状态以参数的形式通过方法传入。
  • 具体享元(Concrete Flyweight)角色:实现抽象享元角色中所规定的接口。
  • 非享元(Unsharable Flyweight)角色:是不可以共享的外部状态,它以参数的形式注入具体享元的相关方法中。
  • 享元工厂(Flyweight Factory)角色:负责创建和管理享元角色。当客户对象请求一个享元对象时,享元工厂检査系统中是否存在符合要求的享元对象,如果存在则提供给客户;如果不存在的话,则创建一个新的享元对象。

🐑案例

最近大火的羊了个羊已消除相同图片的方式进行游戏,如果每个对象都要创建一次实例这些对象就要占用很多的内存空间,我们利用享元模式进行实现。

微信图片_20220923121650.jpg

抽象享元角色

public interface IPicture {

    /**
     * 获取图形
     * @return
     */
    String getShape();
}

具体享元角色

public class FeedingBottlePicture implements IPicture{
    @Override
    public String getShape() {
        return "奶瓶";
    }
}
public class ScissorsPicture implements IPicture{
    @Override
    public String getShape() {
        return "剪刀";
    }
}
public class SmallBellPicture implements IPicture{
    @Override
    public String getShape() {
        return "铃铛";
    }
}

享元工厂

public class PictureFactory {

    private static HashMap<String, IPicture> map;

    private PictureFactory(){
        map = new HashMap<>();
        map.put("奶瓶",new FeedingBottlePicture());
        map.put("剪刀",new ScissorsPicture());
        map.put("铃铛",new SmallBellPicture());
    }

    
    public static IPicture getPicture(String key){
        return map.get(key);
    }

}

使用

public class Demo {

    public static void main(String[] args) {
        //获取铃铛
        IPicture smallBell = PictureFactory.getPicture("铃铛");
        //获取奶瓶
        IPicture feedingBottle = PictureFactory.getPicture("奶瓶");
        //获取剪刀
        IPicture scissors = PictureFactory.getPicture("剪刀");
        
    }
}

🐑优缺点

优点

  • 极大的减少系统中对象的个数,节省内存的开销
  • 避免创建过多的对象,提升性能

缺点

  • 享元模式使得系统更加复杂,需要分离出内部状态和外部状态,这使得程序的逻辑复杂化
  • 为了使对象可以共享,享元模式需要将享元对象的状态外部化,而读取外部状态使得运行时间变长