学习日记-策略模式
来源:互联网 发布:南京 网络问政 编辑:程序博客网 时间:2024/05/16 01:06
-------android培训、java培训、期待与您交流! ----------
策略模式
策略模式就是根据对象的某些属性来操作某些数据时我们可以根据其属性来提供自己的操作策略!
策略模式的用法:
1.许多相关的类仅仅是行为有异。“策略”提供了一种用多个行为中的一个行为来配置一个类的方法。
2.需要使用一个算法的不同变体。
3.算法使用客户不应该知道的数据。可使用策略模式以避免暴露复杂的、与算法相关的数据结构。
4.一个类定义了多种行为,并且这些行为在这个类的操作中以多个条件语句的形式出现。 将相关的条件分支移入它们各自的Strategy类中以代替这些条件语句。下边的例子定义了一个猫类,要根据猫的某项属性来进行排序//定义排序所需接口package com.strategy;public interface Comparable {public int compareTo(Object o);}//定义猫类package com.itcast.stragy;public class Cat implements Comparable{int height;//在此处加的是什么比较器就可以实现怎么样的排序private Comparator comparator=new CatHeightComparator();public Comparator getComparator() {return comparator;}public void setComparator(Comparator comparator) {this.comparator = comparator;}public int getHeight() {return height;}public void setHeight(int height) {this.height = height;}int weight;public Cat(int height, int weight) {super();this.height = height;this.weight = weight;}@Overridepublic int compareTo(Object o) {//if(o instanceof Cat){//Cat c=(Cat)o;//if(this.height>c.height)return 1;//else if(this.height==c.height)return 0;//else return -1;//}//return -100;Cat c=(Cat)o;//在此处使用上不定义的比较器在实现了comparable接口而实现的方法中进行比较return comparator.compare(this, c);}public String toString(){return height+"|"+weight;}}//有时候用户会想要根据自己的需求按照自己的意愿根据某些属性进行排序操作所以定义一个///接口Comparatorpackage com.itcast.stragy;public interface Comparator {int compare(Object o1,Object o2);}//提供其实现类,在其中就可以根据自己的需求定义其实现方式package com.itcast.stragy;public class CatHeightComparator implements Comparator{@Overridepublic int compare(Object o1, Object o2) {Cat c1=(Cat)o1;Cat c2=(Cat)o2;if(c2.weight>c1.weight)return 1;else if(c2.weight==c1.weight)return 0;else return -1;}}
-------android培训、java培训、期待与您交流! ----------
- 学习日记-策略模式
- 2016.12.13学习日记-策略模式
- 学习日记-工厂模式
- 学习日记-代理模式
- 学习日记-观察者模式
- 学习日记-装饰模式
- 设计模式学习日记。
- 策略模式的学习
- 策略模式的学习
- 策略模式学习
- 策略模式学习案例
- 策略模式学习笔记
- 策略模式学习笔记
- 策略模式学习1
- 策略模式学习2
- 策略模式学习
- 策略模式学习
- 策略模式--设计模式学习
- OC中的常见关键字及一些基础概念
- JS中改变时间
- C++ 字符串UTF8与GBK转化
- HDU 1559 最大子矩阵
- win7 64位系统 注册 ocx控件
- 学习日记-策略模式
- 配置NDK syntax error: unexpected end of file 解决
- 谈学习中的改变——有病要诊断,有药要服用
- JavaScript中Array(数组)的属性和方法
- JSP网站利用花生壳在公网上进行访问
- java中Exception in thread "main" java.util.NoSuchElementException
- 批量杀死 MySQL 连接
- Orcal的select into用法
- 浏览器对象模型