代码改变世界

练习使用策略模式

2014-09-23 15:13  星星之火✨🔥  阅读(384)  评论(0编辑  收藏  举报

要求:

  有这样一个Person类:

  public class Person{

    private int id;

    private String  name;

    private int age;             //简便起见,省略了getter and setter方法。

  }

假如有若干个类Person对象存在一个List中,对他们进行排序,按照名字、年龄、id依次排序(正序与倒序两种排序方式)。假如年龄或者姓名重复,按照id的正序进行排序。要求使用策略模式进行。

版本一:

import java.util.ArrayList;
import java.util.List;

public class PersonStrategyTest//client
{
	public static void main(String[] args)
	{
		List list = new ArrayList();
		
		list.add(new Person(1001, "zhangsan", 20));
		list.add(new Person(1004, "lisi", 21));
		list.add(new Person(1002, "lisi", 21));
		list.add(new Person(1003, "lisi", 20));
		list.add(new Person(1005, "wangwu", 20));
		list.add(new Person(1006, "zhaoliu", 20));	
		Person per = new Person(1007, "haifeng", 20);
	
		Environment environment = new Environment(new AscendingSort());
		environment.sort(list);
		System.out.println("按Name-Age-Id依次升序:");
		for(int i=0; i<list.size(); i++)
		{
			Person p = (Person)list.get(i);
			System.out.println(p.getName() + "-" + p.getAge() + "-" + p.getId());
		}
		
		System.out.println("-------我是分界线---------");
		environment.setStrategy(new DescendingSort());
		environment.sort(list);
		System.out.println("按Name-Age-Id依次降序:");
		for(int i=0; i<list.size(); i++)
		{
			Person p = (Person)list.get(i);
			System.out.println(p.getName() + "-" + p.getAge() + "-" + p.getId());
		}
	}
}

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;
	}
}

interface Strategy//抽象策略角色
{
	public void sort(List list);
}

class AscendingSort implements Strategy//具体策略角色,利用冒泡排序的思想实现(按Name—Age—Id)升序排序
{
	public void sort(List list)
	{	
		for(int i=0; i<list.size()-1; i++)
			for(int j=0; j<list.size()-i-1; j++)
			{
				if( ((Person)list.get(j)).getName().compareTo( ((Person)list.get(j+1)).getName() ) > 0 )
				{
					swap(list, j);
				}
				else if( ((Person)list.get(j)).getName().compareTo( ((Person)list.get(j+1)).getName() ) == 0 )
				{
					if( ((Person)list.get(j)).getAge() > ((Person)list.get(j+1)).getAge() )
					{
						swap(list, j);
					}
					else if( ((Person)list.get(j)).getAge() == ((Person)list.get(j+1)).getAge() )
					{
						if( ((Person)list.get(j)).getId() > ((Person)list.get(j+1)).getId() )
						{
							swap(list, j);
						}
					}
				}
			}
	}

	public void swap(List list, int j)//实现两个List元素的交换
	{
		Person ptemp = (Person)list.get(j);
		list.set(j, list.get(j+1));
		list.set(j+1, ptemp);
	}
}

class DescendingSort implements Strategy//实现降序的具体策略角色
{
	public void sort(List list)
	{	
		for(int i=0; i<list.size()-1; i++)
			for(int j=0; j<list.size()-i-1; j++)
			{
				if( ((Person)list.get(j)).getName().compareTo( ((Person)list.get(j+1)).getName() ) < 0 )
				{
					swap(list, j);
				}
				else if( ((Person)list.get(j)).getName().compareTo( ((Person)list.get(j+1)).getName() ) == 0 )
				{
					if( ((Person)list.get(j)).getAge() < ((Person)list.get(j+1)).getAge() )
					{
						swap(list, j);
					}
					else if( ((Person)list.get(j)).getAge() == ((Person)list.get(j+1)).getAge() )
					{
						if( ((Person)list.get(j)).getId() < ((Person)list.get(j+1)).getId() )
						{
							swap(list, j);
						}
					}
				}
			}
	}

	public void swap(List list, int j)
	{
		Person ptemp = (Person)list.get(j);
		list.set(j, list.get(j+1));
		list.set(j+1, ptemp);
	}
}

class Environment//环境角色
{
	Strategy strategy;
	
	public Environment(Strategy strategy)
	{
		this.strategy = strategy;
	}

	public Strategy getStrategy()
	{
		return strategy;
	}

	public void setStrategy(Strategy strategy)
	{
		this.strategy = strategy;
	}
	
	public void sort(List list)
	{
		strategy.sort(list);
	}
}

/*在Eclipse中的输出结果是:
	按Name-Age-Id依次升序:
	lisi-20-1003
	lisi-21-1002
	lisi-21-1004
	wangwu-20-1005
	zhangsan-20-1001
	zhaoliu-20-1006
	-------我是分界线---------
	按Name-Age-Id依次降序:
	zhaoliu-20-1006
	zhangsan-20-1001
	wangwu-20-1005
	lisi-21-1004
	lisi-21-1002
	lisi-20-1003
*/

  版本二:(改善版本一中的排序算法的实现,利用JDK提供的Collections中的sort方法排序,遵循的原则是能用JDK提供的方法实现功能,就尽量不要自己重复造轮子来实现它,因为一般来说,JDK提供的方法性能更好,健壮性也好。但是自己造轮子也有种好处就是磨练自己的技术,所以可能的话也可以试着自己实现一下,再看看用JDK提供的方法是怎么实现,也不失为一种自我提高的办法。)

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class PersonStrategy//client
{	
	public static void main(String[] args)
	{
		List list = new ArrayList();
		
		list.add(new Person(1005, "wangwu", 20));
		list.add(new Person(1006, "zhaoliu", 20));
		list.add(new Person(1001, "zhangsan", 20));
		list.add(new Person(1004, "lisi", 21));
		list.add(new Person(1002, "lisi", 21));
		list.add(new Person(1003, "lisi", 20));	
	
		Environment environment = new Environment(new AscendingSort());
		environment.sort(list);
		
		System.out.println("按Name-Age-Id依次升序:");
		for(int i=0; i<list.size(); i++)
		{
			Person p = (Person)list.get(i);
			System.out.println(p.getName() + "-" + p.getAge() + "-" + p.getId());
		}
		
		System.out.println("-------我是分界线---------");
		environment.setStrategy(new DescendingSort());
		environment.sort(list);
		System.out.println("按Name-Age-Id依次降序:");
		for(int i=0; i<list.size(); i++)
		{
			Person p = (Person)list.get(i);
			System.out.println(p.getName() + "-" + p.getAge() + "-" + p.getId());
		}
	}
}

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;
	}
}

interface Strategy//抽象策略角色
{
	public void sort(List list);
}

class AscendingSort implements Strategy,Comparator//具体策略角色,实现了具体策略的同时实现了Comparator接口(指定比较规则)
{
	public void sort(List list)
	{
		Collections.sort(list, new AscendingSort());
	}
	
	public int compare(Object o1, Object o2)//按照Name—Age-Id依次升序排列,名字按字典序排列,年龄和id按照自然顺序排列
	{
		if( ((Person)o1).getName().compareTo(((Person)o2).getName()) > 0 )
			return 1;
		else if( ((Person)o1).getName().compareTo(((Person)o2).getName()) == 0 )
		{
			if( ((Person)o1).getAge() > ((Person)o2).getAge() )
				return 1;
			else if( ((Person)o1).getAge() == ((Person)o2).getAge() )
			{
				return ((Person)o1).getId() - ((Person)o2).getId() ;
			}
			else return -1;
		}
		else return -1;
	}
	
}

class DescendingSort implements Strategy,Comparator//具体策略角色,实现了具体策略的同时实现了Comparator接口(指定比较规则)
{
	public void sort(List list)
	{
		Collections.sort(list, new DescendingSort());
	}
	
	public int compare(Object o1, Object o2)
	{
		if( ((Person)o1).getName().compareTo(((Person)o2).getName()) < 0 )//按照Name—Age-Id依次降序排列,名字按字典序反序排列,年龄和id按照自然顺序的倒序排列
			return 1;
		else if( ((Person)o1).getName().compareTo(((Person)o2).getName()) == 0 )
		{
			if( ((Person)o1).getAge() < ((Person)o2).getAge() )
				return 1;
			else if( ((Person)o1).getAge() == ((Person)o2).getAge() )
			{
				return -( ((Person)o1).getId() - ((Person)o2).getId() );
			}
			else return -1;
		}
		else return -1;
	}
	
}


class Environment//环境角色
{
	Strategy strategy;
	
	public Environment(Strategy strategy)
	{
		this.strategy = strategy;
	}

	public Strategy getStrategy()
	{
		return strategy;
	}

	public void setStrategy(Strategy strategy)
	{
		this.strategy = strategy;
	}
	
	public void sort(List list)
	{
		strategy.sort(list);
	}
}
/*在Eclipse中的输出结果是:
	按Name-Age-Id依次升序:
	lisi-20-1003
	lisi-21-1002
	lisi-21-1004
	wangwu-20-1005
	zhangsan-20-1001
	zhaoliu-20-1006
	-------我是分界线---------
	按Name-Age-Id依次降序:
	zhaoliu-20-1006
	zhangsan-20-1001
	wangwu-20-1005
	lisi-21-1004
	lisi-21-1002
	lisi-20-1003
*/

  版本三:(利用泛型,改善版本二中需要强制类型转换的部分,从而大大简化了代码,也使代码看起来更加简洁)

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class PersonStrategyUseGeneric
{
	public static void main(String[] args)
	{
		List<Person> list = new ArrayList<Person>();
		
		list.add(new Person(1005, "wangwu", 20));
		list.add(new Person(1006, "zhaoliu", 20));
		list.add(new Person(1001, "zhangsan", 20));
		list.add(new Person(1004, "lisi", 21));
		list.add(new Person(1002, "lisi", 21));
		list.add(new Person(1003, "lisi", 20));	

		Environment environment = new Environment(new AscendingSort());
		environment.sort(list);
		System.out.println("按Name-Age-Id依次升序:");
		for(int i=0; i<list.size(); i++)
		{
			Person p = list.get(i);
			System.out.println(p.getName() + "-" + p.getAge() + "-" + p.getId());
		}
		
		System.out.println("-------我是分界线---------");
		environment.setStrategy(new DescendingSort());
		environment.sort(list);
		System.out.println("按Name-Age-Id依次降序:");
		for(int i=0; i<list.size(); i++)
		{
			Person p = list.get(i);
			System.out.println(p.getName() + "-" + p.getAge() + "-" + p.getId());
		}
	}
}

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;
	}
}

interface Strategy
{
	public void sort(List<Person> list);
}

class AscendingSort implements Strategy,Comparator<Person>
{
	public void sort(List<Person> list)
	{
		Collections.sort(list, new AscendingSort());
	}
	
	public int compare(Person o1, Person o2)
	{
		if( o1.getName().compareTo(o2.getName()) > 0 )
			return 1;
		else if( o1.getName().compareTo(o2.getName()) == 0 )
		{
			if( o1.getAge() > o2.getAge() )
				return 1;
			else if( o1.getAge() == o2.getAge() )
			{
				return o1.getId() - o2.getId() ;
			}
			else return -1;
		}
		else return -1;
	}
	
}

class DescendingSort implements Strategy,Comparator<Person>
{
	public void sort(List<Person> list)
	{
		Collections.sort(list, new DescendingSort());
	}
	
	public int compare(Person o1, Person o2)
	{
		if( o1.getName().compareTo(o2.getName()) < 0 )
			return 1;
		else if( o1.getName().compareTo(o2.getName()) == 0 )
		{
			if( o1.getAge() < o2.getAge() )
				return 1;
			else if( o1.getAge() == o2.getAge() )
			{
				return -( o1.getId() - o2.getId() );
			}
			else return -1;
		}
		else return -1;
	}
	
}

class Environment
{
	Strategy strategy;
	
	public Environment(Strategy strategy)
	{
		this.strategy = strategy;
	}

	public Strategy getStrategy()
	{
		return strategy;
	}

	public void setStrategy(Strategy strategy)
	{
		this.strategy = strategy;
	}
	
	public void sort(List<Person> list)
	{
		strategy.sort(list);
	}
}

/*在Eclipse中的输出结果是:
	按Name-Age-Id依次升序:
	lisi-20-1003
	lisi-21-1002
	lisi-21-1004
	wangwu-20-1005
	zhangsan-20-1001
	zhaoliu-20-1006
	-------我是分界线---------
	按Name-Age-Id依次降序:
	zhaoliu-20-1006
	zhangsan-20-1001
	wangwu-20-1005
	lisi-21-1004
	lisi-21-1002
	lisi-20-1003
*/

 版本四:(进一步优化,详见代码(指定比较规则时,使用this传入参数,以减少对象数量)。简便起见仅提供了按Name进行排序的实现) 

import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.util.Comparator;

public class PersonStrategyPattern//client
{
		public static void main(String[] args)
		{
			List<Person> list = new ArrayList<Person>();
			list.add(new Person("zhangsan", 20, 1001));
			list.add(new Person("lisi", 22, 1002));
			list.add(new Person("lisi", 22, 1003));
			list.add(new Person("lisi", 23, 1004));
			list.add(new Person("wangwu", 24, 1005));
			list.add(new Person("zhaoliu", 25, 1006));
			
			Environment env = new Environment();
			UpNameSort uns = new UpNameSort();
			env.setSortInterface(uns);
			env.sort(list);
			for(int i=0; i<list.size(); i++)
			{
				Person p = list.get(i);
				System.out.println("name: " + p.getName() + ", age: " + p.getAge() + ", id: " + p.getId());
			}
			
			System.out.println("-------------------");
			DownNameSort dns = new DownNameSort();
			env.setSortInterface(dns);
			env.sort(list);
			for(int i=0; i<list.size(); i++)
			{
				Person p = list.get(i);
				System.out.println("name: " + p.getName() + ", age: " + p.getAge() + ", id: " + p.getId());
			}
		}	
}

class Person
{
	private int id;
	private String name;
	private int 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;
	}
	
	public Person(String name, int age, int id)
	{
		this.name = name;
		this.age = age;
		this.id = id;
	}
	
	public Person()
	{
		
	}
}

interface SortInterface//抽象策略角色
{
	public void sort(List<Person> list);
}

class UpNameSort implements SortInterface, Comparator<Person>//具体策略角色,按Name升序排序
{
	public void sort(List<Person> list)
	{
		Collections.sort(list, this);
	}

	public int compare(Person o1, Person o2)
	{
		int result = o1.getName().compareTo(o2.getName());
		
		if(0 == result)
			return o1.getId() - o2.getId();
		
		return result;
	}

}

class DownNameSort implements SortInterface, Comparator<Person>//具体策略角色,按Name降序排列
{
	public void sort(List<Person> list)
	{
		Collections.sort(list, this);

	}
	
	public int compare(Person o1, Person o2)
	{
		int result = o2.getName().compareTo(o1.getName());
		
		if(0 == result)
		{
			return o2.getId() - o1.getId();
		}
		
		return result;
	}
}

class Environment//环境角色
{
	private SortInterface sortInterface;
	
	public Environment(SortInterface sortInterface)
	{
		this.sortInterface = sortInterface;
	}

	public Environment()
	{
		
	}
	
	public void setSortInterface(SortInterface sortInterface)
	{
		this.sortInterface = sortInterface;
	}
	
	public void sort(List<Person> list)
	{
		this.sortInterface.sort(list);
	}
}

/*在Eclipse中的输出结果是:
	name: lisi, age: 22, id: 1002
	name: lisi, age: 22, id: 1003
	name: lisi, age: 23, id: 1004
	name: wangwu, age: 24, id: 1005
	name: zhangsan, age: 20, id: 1001
	name: zhaoliu, age: 25, id: 1006
	-------------------
	name: zhaoliu, age: 25, id: 1006
	name: zhangsan, age: 20, id: 1001
	name: wangwu, age: 24, id: 1005
	name: lisi, age: 23, id: 1004
	name: lisi, age: 22, id: 1003
	name: lisi, age: 22, id: 1002
*/