![](/img/trans.png)
[英]What is the most appropriate design pattern for a notification system with multiple delivery channels?
[英]What is the appropriate design pattern for multiple replacing of specific text or characters
我需要替換數字、html 標簽和特殊字符。 我為每個目的創建了一個方法。 例如,我為 ReplaceSpecialCharacters、ReplaceHTMLTags 和 ReplaceNumeric 創建了方法。 請注意,還有一些額外的替換方法即將出現。我的問題是什么是合適的設計模式? 我正在考慮為此使用策略或工廠模式,裝飾器模式是否適用於此要求?
sample code
var text="12233333333<body>CLEANTEXT!@#$%^&*()</body>"
var cleanText= ReplaceHTMLTags(text)
cleanText= ReplaceNumeric(cleaText)
cleanText= ReplaceSpecialCharacters(cleaText)
這似乎很好地使用了策略模式。 這將幫助您在運行時選擇一種算法,例如 HtmlReplacementBehaviour、NumericReplacementBehaviour。
https://en.wikipedia.org/wiki/Strategy_pattern
https://www.dofactory.com/net/strategy-design-pattern
或者,這也可以通過利用 Builder 來完成,您可以設置一個像
var replacementPlan = new ReplacementBuilder(ReplaceHTMLTags ).Add(ReplaceSpecialCharacters).Add(ReplaceNumeric);
稍后您執行迭代調用各種替換邏輯的替換方法。
我的建議是為每個替換創建一個字符串擴展方法。
public static class MyStringExtension
{
public static string ReplaceHTMLTags(this string text)
{
return Regex.Replace(text, "<.*?>", String.Empty);
}
}
這將允許您將它們鏈接在一起
text.ReplaceHTMLTags().ReplaceNumeric().ReplaceSpecialCharacters()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.