VelocityEngine 和Velocity類解析

在咱們 普通使用velocity的過程當中,或者一開始使用velocitydemo的同窗,總會對這段代碼有印象: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實例。

相關文章
相關標籤/搜索