当前位置:首页 > 开发 > 编程语言 > 编程 > 正文

策略模式小练习

发表于: 2012-10-13   作者:ctrain   来源:转载   浏览:
摘要: 练习: 假如有若干个person对象保存在list对象之中,对它们分别用id,姓名,年龄进行排序(正序/倒序),如果年龄或者姓名重复,则按照id的升序进行排序。要求使用策略模式进行。 Person对象 public class Person { private int id; private String name; private int age; pub
练习:
假如有若干个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> {

	@Override
	public void sort(List<Person> list) {
		Collections.sort(list, this);
	}
	@Override
	public 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());
		}

	}

策略模式小练习

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号