【Velocity官方指南】使用单例模式还是非单例模式

    xiaoxiao2024-01-08  156

    从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; 03... 04/* 05  06  *  Configure the engine - as an example, we are using 07  08  *  ourselves as the logger - see logging examples 09  10  */ 11Velocity.setProperty( 12     Velocity.RUNTIME_LOG_LOGSYSTEM, this); 13/* 14  *  now initialize the engine 15  */ 16Velocity.init(); 17... 18 Template t = Velocity.getTemplate("foo.vm"); 19   

    拆分实例(Separate Instance)

    作为1.2版本后的新功能,你可以创建不同的实例,你可以在JVM(或者Web 容器)中随心所欲的配置你想要的Velocity实例的数量。在你想提供多种不同的配置时,例如:模板字典(template directories),不同的日志工具(logger)将会非常有用。如果你想使用拆分实例,可以用过类: org.apache.velocity.app.VelocityEngine。如上文,这里我们也将提供一个例子

    01</pre> 02 <pre>import org.apache.velocity.app.VelocityEngine; 03 import org.apache.velocity.Template; 04... 05/* 06  *  create a new instance of the engine 07  */ 08VelocityEngine ve = new VelocityEngine(); 09/* 10  *  configure the engine.  In this case, we are using 11  *  ourselves as a logger (see logging examples..) 12  */ 13ve.setProperty( 14     VelocityEngine.RUNTIME_LOG_LOGSYSTEM, this); 15/* 16  *  initialize the engine 17  */ 18ve.init(); 19... 20 Template t = ve.getTemplate("foo.vm");</pre> 21<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包中。如果你觉得有任何不妥当或者需要新增的方法,请随时与我们联系提出您的意见,因为这些类设计的初衷就是用来提供给开发人员进行使用。

     

    转载自 并发编程网 - ifeve.com 相关资源:敏捷开发V1.0.pptx
    最新回复(0)