设计模式之享元模式

1.享元模式概念

        用于减少大量相似对象的内存消耗。通过共享尽可能多的数据来支持大量细粒度的对象,从而节省内存。

2.享元模式组成部分

1)享元接口 (Flyweight): 定义所有具体享元类的公共接口。

2)具体享元类 (Concrete Flyweight): 实现享元接口,并为内部状态存储内部数据。

3)非享元类 (Unshared Concrete Flyweight): 无法或不需要共享的对象。

4)享元工厂 (Flyweight Factory): 负责创建和管理享元对象,确保共享对象的正确管理。

3.举个栗子:

寝室有有一包卫生纸(享元对象),一包湿巾纸(享元对象)放在桌子上(享元工厂),用户(非享元对象)通过使用放在座子上的纸(享元接口)

如下图:

注:这个用缓存解释起来比较好,如果第一次访问某个静态资源,代理服务器(nginx),先看一下自己的缓存里面有没有这个资源,没有就问后端服务器要,向后端服务器要到之后在自己的本地缓存里面存一份,等到下次再有人访问这个请求时,代理服务器(nginx)看了一下自己的本地缓存里面有这个资源,就不用向后端服务器要资源,相当于这次请求走了(nginx)缓存,这样做减轻了后端服务器的压力

4.代码实现

1)享元接口

Paper 类

package org.xiji.Flyweight;

/**
 * Flyweight享元接口
 *
 * 卫生纸接口类
 */
public interface Paper {
    /**
     *
     * 使用卫生纸函数
     */
    void use(String name);
}

2)享元对象

ToiletPaperImpl 卫生纸

package org.xiji.Flyweight;

public class ToiletPaperImpl implements Paper{


    @Override
    public void use(String name) {
        System.out.println(name+"使用了卫生纸");
    }


}

WipesPaper 湿巾纸

package org.xiji.Flyweight;

public class WipesPaper implements Paper{
    @Override
    public void use(String name) {
        System.out.println(name+"使用了湿巾");
    }
}

3)享元工厂

PaperManger

package org.xiji.Flyweight;

/**
 * 享元工厂
 *
 *
 */
public class PaperManger {
    /**
     * 卫生纸
     */
    ToiletPaperImpl toiletPaperImpl ;
    /**
     * 湿巾
     */
    WipesPaper wipesPaper ;
    public Paper getInstance(String paperType) {

        if (paperType.equals("卫生纸")) {

            if (this.toiletPaperImpl == null) {
                this.toiletPaperImpl = new ToiletPaperImpl();

            }
            return  this.toiletPaperImpl;

        }

        if (paperType.equals("湿巾")) {

            if (this.wipesPaper == null) {
                this.wipesPaper = new WipesPaper();

            }

            return this.wipesPaper;
        }

        return null;

    }


}

4)客户端

FlyweightMain

package org.xiji.Flyweight;

/**
 * 享元模式测试类
 */
public class FlyweightMain {
    public static void main(String[] args) {
        String zhangSan = "张三";
        String xiaoJiu = "小久";
        String xiJi = "惜己";
        String liSi = "李四";

        //获取卫生纸
        PaperManger paperManger = new PaperManger();
        Paper toiletPaper = paperManger.getInstance("卫生纸");
        //获取湿巾
        Paper wipesPaper = paperManger.getInstance("湿巾");

        //使用
        toiletPaper.use(zhangSan);
        wipesPaper.use(xiaoJiu);
        toiletPaper.use(xiJi);
        wipesPaper.use(liSi);




    }
}

5)运行结果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值