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

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


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

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

但是由于享元模式缓存的对象不会被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();
    }

你可能感兴趣的:(设计模式)