《设计模式》享元模式

简介: 《设计模式》享元模式

《设计模式》享元模式

定义

  • 享元模式又叫蝇量模式,通过共享已经存在的对象来大幅度减少需要创建的对象数量,避免大量相似对象的开销,从而提高系统资源的利用率,即运用共享技术来有效地支持大量细粒度对象的复用。

享元模式的使用场景

  • 在使用享元模式时需要维护一个存储享元对象的享元池,而这需要耗费一定的系统资源,因此,在需要多次重复使用享元对象时才值得使用享元模式
  • 享元模式常用于系统底层开发,解决系统的性能问题,典型应用场景便是池技术,如数据库连接池、字符串常量池、线程池、缓冲池等。

享元模式中的两种状态

  • 内部状态,不会随着环境的改变而改变的可共享部分,对对象的属性。
  • 外部状态,随环境改变而改变的不可以共享的部分,享元模式的实现要领就是区分应用中的这两种状态,并将外部状态外部化,如对象的方法。

享元模式的成员角色及职责

抽象享元角色(Flyweight):通常是一个接口或抽象类,在抽象享元类中声明了具体享元类公共的方法,这些方法可以向外界提供享元对象的内部数据(内部状态),同时也可以通过这些方法来设置外部数据(外部状态)。

具体享元角色(Concrete Flyweight) :它实现了抽象享元类,称为享元对象。在具体享元

类中为内部状态提供了存储空间。通常可以结合单例模式来设计具体享元类,为每一个具体享元类提供唯一的享元对象。

非享元角色(Unsharable Flyweight) :并不是所有的抽象享元类的子类都需要被共享,不能被共享的子类可设计为非共享具体享元类,当需要一个非共享具体享元类的对象时可以直接通过实例化创建。

享元工厂角色(Flyweight Factory) :负责创建和管理享元角色,当客户对象请求一个享元对象时,享元工厂检查系统中是否存在符合要求的享元对象,如果存在则提供给客户;如果不存在的话,则创建一个新的享元对象。

享元模式的原理类图如下所示

2e718f6de6d94987ae2f2182c528d9c8.png

案例背景:


某知名外包公司同时接了三个类型非常相似的项目,分别是新闻网站、博客网站和某公众号平台,虽然名称听起来不太一样,但是这三个项目本质上都是一个CMS内容管理系统,因此网站的结构、模块非常相似。因此,可以使用享元模式,共享其相关的代码、数据,以及对数据库、内存、硬盘等资源进行共享,减少服务器资源浪费。

设计类图如下所示

2e718f6de6d94987ae2f2182c528d9c8.png

Client

public class Client {
    public static void main(String[] args) {
        WebSiteFactory factory = new WebSiteFactory();
        WebSite newsWebSite = factory.getWebSiteType("新闻");
        newsWebSite.use(new User("sina"));
        WebSite blogWebSite = factory.getWebSiteType("博客");
        blogWebSite.use(new User("csdn"));
        WebSite wxPubWebSite = factory.getWebSiteType("微信公众号");
        wxPubWebSite.use(new User("tencent"));
        System.out.println("网站共有"+factory.getWebSiteCount()+"类");
    }
}

WebSiteFactory

public class WebSiteFactory{
    // 充当池子的作用
    private HashMap<String, ConcreteWebSite> pool = new HashMap<>(4);
    public WebSite getWebSiteType(String type) {
        if (!pool.containsKey(type)) {
            // 创建一个网站,放入池中
            pool.put(type, new ConcreteWebSite(type));
        }
        return (WebSite) pool.get(type);
    }
    public int getWebSiteCount() {
        // 返回池子的大小
        return pool.size();
    }
}

WebSite

public abstract class WebSite {
    public abstract void use(User user);
}

ConcreteWebSite

public class ConcreteWebSite extends WebSite{
    //内部状态,属于共享部分
    private String type = "";
    public ConcreteWebSite(String type) {
        this.type = type;
    }
    @Override
    public void use(User user) {
        System.out.println("网站的发布类型为"+type+"使用的公司是"+user.getName());
    }
}

User

public class User {
    private String name;
    public User(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

享元模式在 JDK 源码 Integer 类中的使用:

public final class Integer extends Number implements Comparable<Integer> {
   /**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.
     */
  private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];
        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;
            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);
            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }
        private IntegerCache() {}
    }
    // 在ValueOf方法中,如果i的范围在[-128,127]之间,则使用享元模式直接返回缓存中的值,属于同一个对象;
    // 否则,重新创建一个对象,因此执行速度也会比直接从缓存中返回值的方式慢
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
}

测试代码

public class Test {
    public static void main(String[] args) {
        Integer i = Integer.valueOf(127);
        Integer j = Integer.valueOf(127);
        Integer k = Integer.valueOf(128);
        Integer l = Integer.valueOf(128);
        Integer m = 127;  // 等同于 Integer.ValueOf(127)
        Integer n = 127;
        System.out.println(i == j);  // true
        System.out.println(k == l); // false
        System.out.println(m == n); // true
        System.out.println( i == m); // true
    }
}
相关文章
|
22天前
|
设计模式 存储 Java
23种设计模式,享元模式的概念优缺点以及JAVA代码举例
【4月更文挑战第6天】享元模式(Flyweight Pattern)是一种结构型设计模式,旨在通过共享技术有效地支持大量细粒度对象的重用。这个模式在处理大量对象时非常有用,特别是当这些对象中的许多实例实际上可以共享相同的状态时,从而可以减少内存占用,提高程序效率
35 4
|
6月前
|
设计模式 存储 缓存
结构型设计模式07-享元模式
结构型设计模式07-享元模式
20 0
|
4月前
|
设计模式 存储 安全
二十三种设计模式全面解析-享元模式(Flyweight Pattern)详解:构建高效共享的对象结构
二十三种设计模式全面解析-享元模式(Flyweight Pattern)详解:构建高效共享的对象结构
|
4月前
|
设计模式
二十三种设计模式全面解析-组合模式与享元模式的结合应用:实现对象的共享和高效管理
二十三种设计模式全面解析-组合模式与享元模式的结合应用:实现对象的共享和高效管理
|
6月前
|
设计模式 存储 Java
【设计模式——学习笔记】23种设计模式——享元模式Flyweight(原理讲解+应用场景介绍+案例介绍+Java代码实现)
【设计模式——学习笔记】23种设计模式——享元模式Flyweight(原理讲解+应用场景介绍+案例介绍+Java代码实现)
29 0
|
13天前
|
设计模式 存储 Java
小谈设计模式(27)—享元模式
小谈设计模式(27)—享元模式
|
1月前
|
设计模式 缓存 Java
设计模式之享元模式
设计模式之享元模式
|
1月前
|
设计模式 存储 缓存
【设计模式】享元模式
【设计模式】享元模式
|
3月前
|
设计模式 存储 缓存
聊聊Java设计模式-享元模式
享元(Flyweight)模式:顾名思义就是**被共享的单元**。意图是复用对象,节省内存,提升系统的访问效率。比如在红白机冒险岛游戏中的背景花、草、树木等对象,实际上是可以多次被不同场景所复用共享,也是为什么以前的游戏占用那么小的内存,却让我们感觉地图很大的原因。
17 3
聊聊Java设计模式-享元模式
|
8月前
|
设计模式 存储 缓存
享元模式【Java设计模式】
享元模式【Java设计模式】
31 0
享元模式【Java设计模式】