策略模式小练习

编程技术  /  houtizong 发布于 3年前   141
练习:
假如有若干个person对象保存在list对象之中,对它们分别用id,姓名,年龄进行排序(正序/倒序),如果年龄或者姓名重复,则按照id的升序进行排序。要求使用策略模式进行。
Person对象
public class Person {private int id;private String name;private int age;public Person(int id, String name, int age) {this.id = id;this.name = name;this.age = age;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}

1、抽象策略类
public interface Strategy {public void sort(List<Person> list);}


2、具体实现类(按id倒序排,其它略)
public class IdDescStrategy implements Strategy, Comparator<Person> {@Overridepublic void sort(List<Person> list) {Collections.sort(list, this);}@Overridepublic int compare(Person p1, Person p2) {return p2.getId() - p1.getId();}}


3、环境类
public class Environment {private Strategy strategy ;public Environment(Strategy strategy) {this.strategy = strategy;}public void setStrategy(Strategy strategy) {this.strategy = strategy;}public void sort(List<Person> list) { this.strategy.sort(list);}}


4、客户端
public static void main(String[] args) {IdDescStrategy iddesc = new IdDescStrategy();Environment environment = new Environment(iddesc);List<Person> list = new ArrayList<Person>();Person p1 = new Person(1, "wangxiaoxiao", 10);Person p2 = new Person(2, "zhangshan", 20);Person p3 = new Person(3, "lisi", 30);Person p4 = new Person(4, "wangwu", 40);Person p5 = new Person(5, "wangke", 50);list.add(p1);list.add(p2);list.add(p3);list.add(p4);list.add(p5);environment.sort(list);for(Person p : list){System.out.println(p.getId()+", "+p.getName()+", "+p.getAge());}}

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!

留言需要登陆哦

技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成

网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];

      订阅博客周刊 去订阅

文章归档

文章标签

友情链接

Auther ·HouTiZong
侯体宗的博客
© 2020 zongscan.com
版权所有ICP证 : 粤ICP备20027696号
PHP交流群 也可以扫右边的二维码
侯体宗的博客