VelocityEngine 和Velocity类解析

在我们 普通使用velocity的过程中,或者一开始使用velocitydemo的同学,总会对这段代码有印象:

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();

 

但是阅读源码会发现在 org.apache.velocity.app包下,会有velocoty和velocityEngine这两个类,里面的方法大同小异,都是init 加setproperty这里设置属性的方法,然后将

VelocityEngine velocity = new VelocityEngine();

这句替换成:

Velocityvelocity = new Velocity();

的时候,依旧可以run成 功。why?

为什么作者要建立两个类似 的文件?

 

看过注释,发现 org.apache.velocity.app.Velocity.类是一个初始化单例的velocity实例的类。

单例模式是一种简单的设计 模式,用最简单的话来说,就是让多个类共享一个实例,让他们能够访问到同样的数据。

对比发现:

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实例。

你可能感兴趣的:(VelocityEngine 和Velocity类解析)