黑马程序员——对象、接口——策略设计模式

来源:互联网 发布:led矩阵灯 编辑:程序博客网 时间:2024/05/29 15:51

------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------


策略设计模式:创建一个能够根据所传递的参数对象的不同,而具有不同行为的方法,这叫做策略设计模式。

下面用一个例子来说明。

import java.util.*;class Processor {public String name() {return getClass().getSimpleName();}Object process(Object input){ return input;}}class Upcase extends Processor {String process (Object input){ //Covariant returnreturn ((String)input).toUpperCase();}}class Downcase extends Processor {String process (Object input){return ((String)input).toLowerCase();}}class Splitter extends Processor {String process (Object input){//The split() argument divides a String into pieces: return Arrays.toString(((String)input).split(" "));}}public class Apply {public static void process (Processor p, Object s) {System.out.println(" Using professor " + p.name());System.out.println(p.process(s));}public static String s = "Disagreement with beliefs is by different incorrect";public static void main(String[] args){process(new Upcase(),s);process(new Downcase(),s);process(new Splitter(),s);}}/*Output:Using professor UpcaseDISAGREEMENT WITH BELIEFS IS BY DIFFERENT INCORRECTUsing professor Downcasedisagreement with beliefs is by different incorrectUsing professor Splitter[Disagreement, with, beliefs, is, by, different, incorrect]*/
上例中,Apply.process() 方法可以接受任何类型的processor,这便是策略设计模式。process方法包含算法中不变的部分,而策略包含变化的部分。在这里策略便是传递进去的参数对象,其包含了要执行的代码。

0 0
原创粉丝点击