码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-05-06 20:49:00      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:执行   blog   font   java   nbsp   print   代码   code   参数   

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编程思想》:设计模式(不定期更新)

标签:执行   blog   font   java   nbsp   print   代码   code   参数   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!