《设计模式》享元模式

《设计模式》设计模式的基本原则
《设计模式》单例模式
《设计模式》工厂模式
《设计模式》原型模式
《设计模式》建造者模式
《设计模式》适配器模式
《设计模式》桥接模式
《设计模式》装饰者模式
《设计模式》组合模式
《设计模式》外观模式
《设计模式》享元模式
《设计模式》代理模式
《设计模式》模板方法模式
《设计模式》命令模式

《设计模式》享元模式

定义

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

享元模式的使用场景

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

享元模式中的两种状态

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

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

  • 抽象享元角色(Flyweight):通常是一个接口或抽象类,在抽象享元类中声明了具体享元类公共的方法,这些方法可以向外界提供享元对象的内部数据(内部状态),同时也可以通过这些方法来设置外部数据(外部状态)。
  • 具体享元角色(Concrete Flyweight) :它实现了抽象享元类,称为享元对象。在具体享元
    类中为内部状态提供了存储空间。通常可以结合单例模式来设计具体享元类,为每一个具体享元类提供唯一的享元对象。
  • 非享元角色(Unsharable Flyweight) :并不是所有的抽象享元类的子类都需要被共享,不能被共享的子类可设计为非共享具体享元类,当需要一个非共享具体享元类的对象时可以直接通过实例化创建。
  • 享元工厂角色(Flyweight Factory) :负责创建和管理享元角色,当客户对象请求一个享元对象时,享元工厂检查系统中是否存在符合要求的享元对象,如果存在则提供给客户;如果不存在的话,则创建一个新的享元对象。

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

在这里插入图片描述

案例背景

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

设计类图如下所示

在这里插入图片描述

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
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43252521/article/details/128491498
今日推荐