Java学习笔记20 策略模式(Stratag…

来源:互联网 发布:php csdn博客 编辑:程序博客网 时间:2024/06/05 14:40
1.什么是策略模式(Strategy)
   1)定义一组算法,将每个算法都封装起来,并且让它们之间可以互换
   2)策略模式使这些算法在客户端调用它们的时候能够互不影响地变化
2.策略模式的意义
   1)策略模式使开发人员能够开发出许多可替换的部分组成的软件,并且各部分之间是弱连接的关系
   2)弱连接的特性使软件具有更强的扩展性,易于维护:尤其是,它大大提高了软件的可重用性
3.策略模式的组成
   1)抽象策略角色:策略类,通常由一个接口或抽象类充当
   2)具体策略角色:包装了相关的算法和行为
   3)环境角色:持有一个策略类的引用,最终在客户端利用多态,通过引入具体策略角色实现功能
4.策略模式的实现
   1)策略模式的用意是针对一组算法,将每一个算法封装到具有共同接口的独立类中,从而使得它们可以相互替换。
   2)策略模式使得算法可以在不影响到客户端的情况下发生变化,使用策略模式可以把行为和环境分隔开来
   3)环境类负责维护和查询行为类,各种算法和环境独立开来,算法的修改都不会影响到环境和客户端
5.策略模式的编写步骤
   1)对策略对象定义一个公共接口
   2)编写策略类,该类实现了1)所定义的公共接口
   3)在使用策略对象的类中保存一个对策略对象的引用
   4)在使用策略对象的类中,实现对策略对象的set和get方法或者使用构造方法完成赋值

策略模式的具体应用:要求:假如有若干个类Person的对象存在List当中,对它们进行排序,按照名字进行排序(分正序和倒序两种排序方式),当姓名重复时,按照id的正序进行排序,(利用策略模式进行)
代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


public class Client
{
 
 public static void main(String[] args)
 {
  Person p1 = newPerson("zhangsan", 20, 101);
  Person p2 = new Person("lisi",20, 102);
  Person p3 = newPerson("wangwu", 22, 103);
  Person p4 = newPerson("zhangsan", 21,104);
  
  ArrayList<Person>list = new ArrayList<Person>();
  list.add(p1);
  list.add(p2);
  list.add(p3);
  list.add(p4);
  
  Environment roment = newEnvironment();
  //自然顺序排序
  UpSortOfName upSort = newUpSortOfName();
  roment.setSorter(upSort);
  roment.sort(list);
  for(Person i : list)
  {
   System.out.println(i.name + " " + i.age + " " + i.id);
  }
  System.out.println("****************");
  //倒序排序
  DownSortOfName downSort = newDownSortOfName();
  roment.setSorter(downSort);
  roment.sort(list);
  for(Person i : list)
  {
   System.out.println(i.name + " " + i.age + " " + i.id);
  }
 }
}

 class Person
{
  String name;
  int age;
  int id;
  public Person(String name, intage, int id)
  {
   this.name =name;
   this.age=age;
   this.id =id;
  }
}
 
interface Sorter
{
 public voidsort(List<Person> list);
 
}

class UpSortOfName implementsSorter,Comparator<Person>
{
 public voidsort(List<Person> list)
 {
  Collections.sort(list,this);
 }
 public int compare(Person p1,Person p2)
 {
  int value =p1.name.compareTo(p2.name);
  if(0 == value)
  {
   return p1.id- p2.id;
  }
  return value;
 }
}

class DownSortOfName implementsSorter,Comparator<Person>
{
 public voidsort(List<Person> list)
 {
  Collections.sort(list,this);
 }
 public int compare(Person p1,Person p2)
 {
  int value =p2.name.compareTo(p1.name);
  if(0 == value)
  {
   return p1.id- p2.id;
  }
  return value;
 }
}

class Environment
{
 Sorter sorter;
 public Environment(Sorter sorter)
 {
  this.sorter = sorter;
 }
 public Environment()
 {
  
 }
 public voidsort(List<Person> list)
 {
  this.sorter.sort(list);
 }
 public void setSorter(Sorter sorter) {
  this.sorter = sorter;
 }
}

















0 0