设计模式之享元模式

Java48

本文通过优化买票的重复流程来说明享元模式,为了加深对该模式的理解,会以String和基本数据类型的包装类对该模式的设计进一步说明。

一、引出问题

鉴于小王此前的出色表现,老王决定带小王去旅游,但他在火车站买票时却排起了长队。

[En]

In view of Xiao Wang's previous excellent performance, Lao Wang decided to take Xiao Wang for a trip, but he was stuck in a long line when buying tickets at the railway station.

二、概念和使用

上述重用过程实际上是共享元模式的设计思想,它是一种构造性的设计模式,通过共享数据使同一对象只在内存中有一个实例,从而降低系统创建对象实例的性能消耗。

[En]

The reuse process mentioned above is actually the design idea of sharing meta-pattern, which is one of the constructive design patterns, which makes only one instance of the same object in memory by sharing data, so as to reduce the performance consumption of creating object instances by the system.

享元模式包含三个角色:

(1)抽象享元Flyweight类:享元对象抽象基类或接口。

(2)具体享元ConcreteFlyweight类:实现抽象享元类。

(3)享元工ctory类:厂FlyweightFa享元模式的核心模块,负责管理享元对象池、创建享元对象,保证享元对象可以被系统适当地共享。

当客户端对象调用共享元对象时,共享元工厂角色检查系统中是否已经存在限定的共享元对象,如果是,则共享元工厂角色提供现有的共享元对象;如果没有,则创建一个。

[En]

When a client object calls a shared meta-object, the shared meta-factory role checks whether there is already a qualified shared meta-object in the system, and if so, the shared meta-factory role provides the existing shared meta-object; if not, create one.

输入验证码查看隐藏内容

扫描二维码关注本站微信公众号 Johngo学长
或者在微信里搜索 Johngo学长
回复 svip 获取验证码
wechat Johngo学长