其他分享
首页 > 其他分享> > 设计模式——结构型之享元模式

设计模式——结构型之享元模式

作者:互联网

设计模式——结构型之享元模式


如果一个类的大量实例的部分属性都相同,就把这些属性抽离成新类,这样的类结构叫享元模式

享元模式就是不同实例的成员变量共享同一个实例,降低内存占用

但是由于享元模式缓存的对象不会被jvm回收,除非验证过有性能提升,否则不要滥用

享元模式由3部分组成:

享元类:

public class FlyWeight {
    private String paramA;
    private String paramB;
    private String paramC;

    public FlyWeight(String paramA, String paramB, String paramC) {
        this.paramA = paramA;
        this.paramB = paramB;
        this.paramC = paramC;
    }
    //get、set方法省略
    //设置equals是为了比较享元实例中的成员变量是否相同,你也可以自己后面手动比较
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        FlyWeight flyWeight = (FlyWeight) o;
        return Objects.equals(paramA, flyWeight.paramA) && Objects.equals(paramB, flyWeight.paramB) && Objects.equals(paramC, flyWeight.paramC);
    }

    @Override
    public int hashCode() {
        return Objects.hash(paramA, paramB, paramC);
    }
}

原始类:

public class Origin {

    private FlyWeight flyWeight;
    private String paramD;
    private String paramE;

    public Origin(FlyWeight flyWeight, String paramD, String paramE) {
        this.flyWeight = flyWeight;
        this.paramD = paramD;
        this.paramE = paramE;
    }

    public void doSth(){
        System.out.println("flyWeight:"+flyWeight+",paramD:"+paramD+",paramE:"+paramE);
    }
}

工厂类:

public class FlyWeightFactory {

    private static final List<FlyWeight> FLY_WEIGHTS = new ArrayList<>();

    public static FlyWeight getFlyWeight(String paramA,String paramB,String paramC){
        final FlyWeight expectFlyWeight = new FlyWeight(paramA, paramB, paramC);
        for (FlyWeight haveFlyWeight : FLY_WEIGHTS) {
            if(expectFlyWeight.equals(haveFlyWeight)){
                return haveFlyWeight;
            }
        }
        FLY_WEIGHTS.add(expectFlyWeight);
        return expectFlyWeight;
    }

}

使用:

public static void main(String[] args) {
        final FlyWeight flyWeight1 = FlyWeightFactory.getFlyWeight("paramA", "paramB", "paramC");
        final Origin origin1 = new Origin(flyWeight1,"paramD1","paramE1");
        origin1.doSth();
        final FlyWeight flyWeight2 = FlyWeightFactory.getFlyWeight("paramA", "paramB", "paramC");
        final Origin origin2 = new Origin(flyWeight2,"paramD2","paramE2");
        origin2.doSth();
    }

标签:享元,paramC,String,paramA,paramB,FlyWeight,设计模式,public,结构型
来源: https://blog.csdn.net/weixin_39841589/article/details/111964336