//文本替换策略 abstract class TextStrategy { protected String text;
public TextStrategy(String text) { this.text = text; } public abstract String replace(); } //替换算法1:将文本中"@r@n"替换为"@n" class StrategyOne extends TextStrategy { public StrategyOne(String text) { super(text); } public String replace() { System.out.println(“StrategyOne:”); String result = text.replaceAll("@r@n", "@n")); return result; } } //替换算法2:将文本中"@n"替换为"@r@n" class StrategyTwo extends TextStrategy { public StrategyTwo(String text) { super(text); } public String replace() { System.out.println(“StrategyTwo:”); String result = text.replaceAll(“@n", "@r@n")); return result; } } public class TextCharChange { public static void replace(TextStrategy strategy) { strategy.replace(); } public static void main(String[] args){ String testText1 = "This is a test text!!@n Oh! Line Return!!@n"; String testText2 = This is a test text!!@r@n Oh! Line Return@r@n"; TextCharChange.replace(new StrategyOne(testText2)); TextCharChange.replace(new StrategyTwo(testText1)); } }