首页 > 编程语言 > 详细

《java编程思想》:设计模式(不定期更新)

时间:2017-05-06 20:25:50      阅读:330      评论:0      收藏:0      [点我收藏+]
1.策略设计模式

  创建一个能够根据所传递的参数对象的不同而具有不同的方法,被称为策略设计模式。这类方法包含索要执行的算法中固定不变的部分,而“策略”包含变化的部分。策略就是传递进去的参数对象。在下面的代码示例中,Process对象就是策略。应用在了s上。

代码示例:

class Process {
    public String getName(){
        return getClass().getSimpleName();
    }
    Object process(Object input){
        return input;
    }
}

class Upcase extends Process {
    String process(Object input){
        return ((String)input).toUpperCase();
    }
}

class Lowercase extends Process {
    String process(Object input){
        return ((String)input).toLowerCase();
    }
}

public class Strategy{
    public static void process(Process p,Object s){
        System.out.println("Using Process " + p.getName());
        System.out.println(p.process(s));
    }
    public static String s="this is strategy design model!";

    public static void main(String[] args) {
        process(new Upcase(),s);
        process(new Lowercase(),s);
    }
}
输出:
Using Process Upcase
THIS IS STRATEGY DESIGN MODEL!
Using Process Lowercase
this is strategy design model!

 

 

《java编程思想》:设计模式(不定期更新)

原文:http://www.cnblogs.com/don9/p/6817924.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!