侧边栏壁纸
博主头像
Elltor

用心发现生活,积极面对工作、事,坚持每天让自己进步一点。

  • 累计撰写 164 篇文章
  • 累计创建 1 个标签
  • 累计收到 10 条评论

目 录CONTENT

文章目录

设计模式|享元模式 —— 分享是一种美德

Elltor
2020-10-29 / 0 评论 / 0 点赞 / 51 阅读 / 1,694 字

运用享元模式(Flyweight)可以有效地支持大量细粒度的对象。

类结构

image.png

代码

package com.elltor.designpattern.Flyweight;

public interface Flyweight {
    void operation(int i);
}
package com.elltor.designpattern.Flyweight;

public class ConcreteFlyweight implements Flyweight {

    @Override
    public void operation(int i) {
        System.out.println("具体的享元对象: "+i);
    }
}
package com.elltor.designpattern.Flyweight;

import java.util.HashMap;

public class FlyweightFcatory {
    private HashMap<String,ConcreteFlyweight> flyweightMap = new HashMap<>();

    public FlyweightFcatory() {
        flyweightMap.put("A",new ConcreteFlyweight());
        flyweightMap.put("B",new ConcreteFlyweight());
        flyweightMap.put("C",new ConcreteFlyweight());
        flyweightMap.put("D",new ConcreteFlyweight());
        flyweightMap.put("E",new ConcreteFlyweight());
    }

    public Flyweight getFlyweight(String key){
        return flyweightMap.get(key);
    }
}
package com.elltor.designpattern.Flyweight;

public class UnsharedFlyweight implements Flyweight {
    @Override
    public void operation(int i) {
        System.out.println("不被共享的享元对象: "+i);
    }
}
package com.elltor.designpattern.Flyweight;

public class Main {
    public static void main(String[] args) {
        int i = 100;
        FlyweightFcatory factory = new FlyweightFcatory();

        Flyweight flyweightA = factory.getFlyweight("A");
        flyweightA.operation(i);

        Flyweight flyweightB = factory.getFlyweight("B");
        flyweightB.operation(i*2);

        Flyweight flyweightC = factory.getFlyweight("C");
        flyweightC.operation(i*3);

        Flyweight flyweightD = factory.getFlyweight("D");
        flyweightD.operation(i*4);

        Flyweight flyweightE = factory.getFlyweight("E");
        flyweightE.operation(i*5);
    }

}
//打印结果
具体的享元对象: 100
具体的享元对象: 200
具体的享元对象: 300
具体的享元对象: 400
具体的享元对象: 500

抽离表象, 用同一个对象表示不同"外观"的对象, 这些"外观"的差异是由数据的不同而产生。

0

评论区