设计模式之策略Strategy模式

Strategy模式是定义一系列算法,把这些算法定义成一个新的类,在运行的时候动态选择需要的算法。

策略模式的ULM图:

策略模式的例子如下

策略模式的例子如下:

//文本替换策略
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)); 
}
}

 

State模式和Strategy模式很类似,但是又有很明显的区别:

1 State模式设定状态的变化,根据状态的变化来返回相应的处理。

2 Strategy模式是根据需求和场景选择适合的算法。

JDK中策略模式的应用:

java.util.concurrent.ThreadPoolExecutor.AbortPolicy
java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy
java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy
java.util.concurrent.ThreadPoolExecutor.DiscardPolicy
java.util.Comparator


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值