Flyweight Pattern

Flyweight pattern is to help re-use created object if the object is fine-grained and the key parameter is not changed, in this case we can avoid to waste memory.

The parameters can be sperate to 2 parts, first part is internal parameters, like key parameter; the second parts are parameters which can be assigned from outside.

The implementation way is, we create a map to record the objects we have created based on key parameter, next time if we create new object with same key , we will not create it but directly ask for map to return, the other parameters we will assign values from outside.

Below example is we will create many tree nodes on the map, but which type of the tree is will be part of internal parameter, tree location are parameters assigned from outside like when we initial the map.

public Tree createTree(String type) {
    if (treeMap.containsKey(type)){
        return treeMap.get(type);
    }
    Tree tree = new Tree(type);
    treeMap.put(type, tree);
    System.out.println("Create new tree object");
    return tree;
}

When we initial the map, we can create tree node objects, but insde, whether we create new tree we will base on whether tree key parameter is changed or not. In below example, we only create 2 tree objects, even though we will have 20 tree node objects.

String type = "normal";
TreeFactory factory = new TreeFactory();
for (int i = 0; i < 10; i++) {
    int x = (int) (Math.random() * 100);
    int y = (int) (Math.random() * 100);
    TreeNode treenote = new TreeNode(x, y, factory.createTree(type));
    System.out.println(treenote);
}

type = "tall";
for (int j = 0; j < 10; j++) {
    int x = (int) (Math.random() * 100);
    int y = (int) (Math.random() * 100);
    TreeNode treenote = new TreeNode(x, y, factory.createTree(type));
    System.out.println(treenote);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值