本来我是想完成一个占位符(placeholder)字符串处理功能实现!之前我发过帖子求助,后来发现真笨,用String的replace方法就可以实现的。
帖子在此:
http://topic.csdn.net/u/20111227/20/f4e4f380-069e-4d34-be66-175f82a5c1f9.html
首先,我设计了一个类—信息包裹(MessageBundle),但由于信息包裹内的信息大部分都是带有占位符的字符串!
程序响应给外部系统时,就必需把这些占位符替换成程序运行时的值。
例如:
要查找与含词“FindMe”的相匹配用户
信息包裹内的字符串:
没有发现与[${username}]相匹配的用户!
那么程序运行时给外部系统的信息提示可能为
“没有发现与[FindMe]相匹配的用户!”
一开始我就设想,新建个类SentenceForm及为其创建方法
- Java code
void replaceVariableWith(String theVaribaleName,String theVariableValue)
不就得了。调用此方法的风格就形如这样:
- Java code
sentenceForm.replaceVariableWith("username","FindMe");
但我想了想,如果是我,当然知道这语句是什么意思。但别人有时会出现混淆(当然机率可能很小),读者看代码时,此代码含义是:
sentenceForm replace variable "username" with "FindMe"
还是(在没有看方法签名的情况下,反正我看着上面的调用风格有点不是味道)
sentenceForm replace variable with ("username","FindMe")
意思把变量"username"的名字改一个新名字"FindMe"。或者还是其它什么意思啦。
于是我就想调用此方法的风格要是这样就好了
sentenceForm.replace("username").with("FindMe")
这样应该不会有误解了吧!
如是就有了最终的代码:
- Java code
package com.dongantech.eshop.web.util;public class SentenceForm { private String sentenceForm = null ; private String replacedVariableName = "" ; public void setSentenceForm(String theSentenceForm){ sentenceForm = theSentenceForm; } public String getSentenceForm(){ return sentenceForm; } public SentenceForm replaceVariable(String theVariableName){ replacedVariableName = theVariableName ; return this ; } public SentenceForm with(String theValue){ String replacedVariable = "${"+replacedVariableName+"}"; sentenceForm.replace(replacedVariable,theValue) ; return this ; }}
当然,这只是链式调用的另外一种用途。但我想分享一下自己的心得。。。仅此而已!
------解决方案--------------------
也许用Builder模式更简单更直观。
类似于:
MessageBuilder mb = new MessageBuilder(sMsgTemplate);
mb.setParamValues(mapValues);
mb.toSting();
其实我觉得直接这样也没啥不清晰的啊:
String MessageBuilderUtil.prepareMsg(String sMsgTemplate, HashMap mapValues);