在咱们 普通使用velocity的过程当中,或者一开始使用velocity作demo的同窗,总会对这段代码有印象:apache
VelocityEngine velocity = new VelocityEngine();
VelocityContext context = new VelocityContext();
context.put("name", "czy");
Template template = velocity.getTemplate("/src/main/resources/test.vm");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
template.merge(context, writer);
writer.flush();
writer.close();app
可是阅读源码会发如今 org.apache.velocity.app包下,会有velocoty和velocityEngine这两个类,里面的方法大同小异,都是init 加setproperty这里设置属性的方法,而后将oop
VelocityEngine velocity = new VelocityEngine();spa
这句替换成:设计
Velocityvelocity = new Velocity();orm
的时候,依旧能够run成 功。why?blog
为何做者要创建两个相似 的文件?内存
看过注释,发现 org.apache.velocity.app.Velocity.类是一个初始化单例的velocity实例的类。ci
单例模式是一种简单的设计 模式,用最简单的话来讲,就是让多个类共享一个实例,让他们可以访问到一样的数据。get
对比发现:
Velocity类中使用 init方法里是使用了RuntimeSingleton.init();
在 RuntimeSingleton类中,使用到的运行实例是静态new出来的。
private static RuntimeInstance ri = new RuntimeInstance();
而在 org.apache.velocity.app.VelocityEngine类中,并无一个单例类来初始化,每次都会使用
private RuntimeInstance ri = new RuntimeInstance()
来建立一个新的运行实例,这样就使得每一个velocity引擎都会 拥有各自的实例,互不干扰。
从RuntimeSingleton类的注释来看:
/**
* This is the Runtime system for Velocity. It is the
* single access point for all functionality in Velocity.
* It adheres to the mediator pattern and is the only
* structure that developers need to be familiar with
* in order to get Velocity to perform.
*
* The Runtime will also cooperate with external
* systems like Turbine. Runtime properties can
* set and then the Runtime is initialized.
*
* Turbine for example knows where the templates
* are to be loaded from, and where the velocity
* log file should be placed.
*/
velocity和外部合做的项目,例如turbine,就使用的这个类来实例化 velocity引擎。 咱们在本身写demo 的时候,却是无所谓使用哪一个类,通常也不会产生不少实例,可是在生产环境就要注意,一旦不使用单例,当访问量过大时,会将内存消耗的不少,每个请求都会 产生一个新的velocity实例。