305
阿裏雲
技術社區[雲棲]
【Velocity官方指南】使用單例模式還是非單例模式
從Velocity 1.2以後的版本,開發者對於Velocity引擎的使用有了兩種方式,單例模型(Singleton)以及多個獨立實例模型。Velocity的核心部分也采用了這兩種模型,目的是為了讓Velocity可以更容易與你的JAVA應用相集成。
單例模式(Singleton):
這是一個遺留(Legacy)模式,在這種模式下隻有一個Velocity的引擎在JVM(或者是WEB容器,這取決於你的環境)中會被實例化,同時被全部程序所共享。這對本地化的配置以及可被分享的其他資源來說是十分方便的。舉個例子,在Servlet 2.2以上的版本中,將Velocity實例化並且采用單例模型提供給一個web程序使用是一種十分值得推薦的模式,這樣web應用中的servlet可以共享資源,比如:模板(templates),日誌工具(logger)等等。單例模式可以通過如下的類進行訪問: org.apache.velocity.app.Velocity,下文中會給出一個具體的例子
01 |
import org.apache.velocity.app.Velocity;
|
02 |
import org.apache.velocity.Template;
|
06 |
* Configure the engine - as an example, we are using
|
08 |
* ourselves as the logger - see logging examples
|
12 |
Velocity.RUNTIME_LOG_LOGSYSTEM, this);
|
14 |
* now initialize the engine
|
18 |
Template t = Velocity.getTemplate( "foo.vm" );
|
拆分實例(Separate Instance)
作為1.2版本後的新功能,你可以創建不同的實例,你可以在JVM(或者Web 容器)中隨心所欲的配置你想要的Velocity實例的數量。在你想提供多種不同的配置時,例如:模板字典(template directories),不同的日誌工具(logger)將會非常有用。如果你想使用拆分實例,可以用過類: org.apache.velocity.app.VelocityEngine。如上文,這裏我們也將提供一個例子
02 |
<pre> import org.apache.velocity.app.VelocityEngine;
|
03 |
import org.apache.velocity.Template;
|
06 |
* create a new instance of the engine
|
08 |
VelocityEngine ve = new VelocityEngine(); |
10 |
* configure the engine. In this case, we are using
|
11 |
* ourselves as a logger (see logging examples..)
|
14 |
VelocityEngine.RUNTIME_LOG_LOGSYSTEM, this);
|
16 |
* initialize the engine
|
20 |
Template t = ve.getTemplate( "foo.vm" );</pre>
|
如你所見,他們的使用非常的簡單明了。除了一些細微的語義上的區別外,使用單例或者可拆分實例對你的上層應用或者模板來說並沒有太大的區別.
作為一個程序員,如果你想采用單例模式,需要訪問org.apache.velocity.app.Velocity這個類,如果采用非單例模式(拆分實例)的話隻需訪問類 org.apache.velocity.app.VelocityEngine
在任何時候請不要在程序中使用內置的 在包org.apache.velocity.runtime 下的Runtime, RuntimeConstants, RuntimeSingleton or RuntimeInstance 類,因為這些類的設計僅僅是供velocity內部使用,並且未來可能會被修改。請按我們前文描述的,開發人員所需使用的類文件在 org.apache.velocity.app包中。如果你覺得有任何不妥當或者需要新增的方法,請隨時與我們聯係提出您的意見,因為這些類設計的初衷就是用來提供給開發人員進行使用。
最後更新:2017-05-22 16:02:50