设计模式(十二)享元模式

享元模式用于高效地管理大量相似对象,通过建立缓存池实现对象复用。在游戏开发场景中,例如汽车和摩托车这类载具,可以避免每次创建新对象,提高性能。接口定义了游戏对象的基本行为,缓存池作为工厂负责对象的复用,测试显示对象成功被复用。
摘要由CSDN通过智能技术生成

如果系统中可能存在大量相同的对象,那么我们可以建立缓存池之类的东西,将这些重复对象进行复用。这种设计模式就是享元模式。

假设有一个游戏,里面需要汽车和摩托车两种载具。我们希望这些载具可以在游戏中复用,而不是每次都创建新对象。所以这个例子就可以使用享元模式来做。

首先是汽车和摩托车的抽象。我们使用Visible接口表示这个对象将要在游戏中显示。

public interface Visible {
    void show();
}

public class Car implements Visible {
    private int id;

    public Car(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    @Override
    public void show() {
        System.out.println("This is a car " + id);
    }
}

public class Motorcycle implements Visible {
    private int id;

    public Motorcycle(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    @Override
    public void show() {
        System.out.println("THis is a motorcycle "+id);
    }
}

然后是一个缓存池,充当着这些对象的工厂。我们可以将池中的对象复用。这里直接将对象放到了HashMap中了。

public class ObjectPool {
    private HashMap<Integer, Car> carMap = new HashMap<>();
    private HashMap<Integer, Motorcycle> motorcycleMap = new HashMap<>();

    public void putCar(Car car) {
        carMap.put(car.getId(), car);
    }

    public Car getCar(int id) {
        return carMap.get(id);
    }

    public void putMotorcycle(Motorcycle motorcycle) {
        motorcycleMap.put(motorcycle.getId(), motorcycle);
    }

    public Motorcycle getMotorcycle(int id) {
        return motorcycleMap.get(id);
    }
}

最后再来测试一下。可以看到对象被成功的复用了。

    public void run() {
        ObjectPool pool = new ObjectPool();
        pool.putCar(new Car(1));
        pool.putCar(new Car(2));
        pool.putCar(new Car(3));
        pool.putCar(new Car(4));
        pool.putCar(new Car(5));

        pool.putMotorcycle(new Motorcycle(1));
        pool.putMotorcycle(new Motorcycle(2));
        pool.putMotorcycle(new Motorcycle(3));

        pool.getCar(1).show();
        pool.getCar(2).show();
        pool.getCar(3).show();

        pool.getMotorcycle(1).show();
        pool.getMotorcycle(2).show();

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值