Java设计模式 - 蝇量模式(享元模式)

1. 定义

运用共享技术有效地支持大量的细粒度对象的复用。

2. 角色

  • Flyweight:抽象蝇量类
  • ConcreteFlyweight:具体蝇量类
  • FlyweightFactory:蝇量工厂

     

3. 特点

  • 优点:减少内存中对象的数量,使得相同或相似的对象在内存中可以集中管理。
  • 缺点:该模式需要分离出内部状态和外部状态,使程序的逻辑变得复杂。

4. 示例

公园里有许多树和草,需要展示它们的坐标。如果为每一棵树或草都创建一个对象,会耗费许多内存,因此仅创建一个树的对象和一个草的对象,通过将它们的坐标传入来展示。

Plant:

public abstract class Plant {

    public Plant() {}

    public abstract void display(int x, int y);
}

具体蝇量类(即树和草):

// Tree
public class Tree extends Plant {

    @Override
    public void display(int x, int y) {
        System.out.println("树:" + x + ", " + y);
    }
}


// Grass
public class Grass extends Plant {

    @Override
    public void display(int x, int y) {
        System.out.println("草:" + x + ", " + y);
    }
}

PlantFactory:

import java.util.HashMap;
import java.util.Map;

public class PlantFactory {

    private Map<Integer, Plant> plants;

    public PlantFactory() {
        plants = new HashMap<>();
    }

    public Plant getPlant(int type){
        if (!plants.containsKey(type)) {
            if (type == 1) {
                Plant tree = new Tree();
                plants.put(1, tree);
                return tree;
            } else if (type == 0) {
                Plant grass = new Grass();
                plants.put(0, grass);
                return grass;
            }
        }
        return plants.get(type);
    }
}

测试类:

public class TestFlyweight {

    public static void main(String[] args) {

        int[] xArrays = new int[5];
        int[] yArrays = new int[5];
        int[] typeArrays = new int[5];

        for (int i = 0; i < 5; i++) {
            xArrays[i] = (int) (Math.random() * 5);
            yArrays[i] = (int) (Math.random() * 5);
            typeArrays[i] = (int) (Math.random() * 5) % 2;
        }

        PlantFactory plantFactory = new PlantFactory();
        for (int i = 0; i < 5; i++) {
            plantFactory.getPlant(typeArrays[i]).display(xArrays[i], yArrays[i]);
        }
    }
}


// 输出
// 树:3, 1
// 树:0, 2
// 草:3, 2
// 树:0, 1
// 树:4, 1

 

参考:
1. 《Head First 设计模式》

2. 《图说设计模式》https://design-patterns.readthedocs.io/zh_CN/latest/structural_patterns/flyweight.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值