设想有一个类Human,它有Name,Age,Hight,Weight等属性。如下:
class Human
{
private string _name;
public string Name { get;set;}
private int _age = -1;
public int Age { get;set;}
private int _hight = -1;
public int Hight { get;set;}
private int _weight = -1;
public int Weight { get;set;}
public Human(string name, int age, int hight, int weight)
{
_name = name;
_age = age;
_hight = hight;
_weight = weight;
}
}
现在要写一个对2个Human实例比较的类MyClass,如下:
class MyClass
{
int _comparetype = -1;
public void SetCompareType(int type)
{
_comparetype = type;
}
public int Compare(Human h1, Human h2)
{
if (_comparetype == 1)//年龄par
{
if (h1.Age > h2.Age)
{
return 1;
}
else if (h1.Age < h2.Age)
{
return -1;
}
else
return 0;
}
if (_comparetype == 2) //体重
{
//・・・・
}
}
}
这里,Compare这个方法非常复杂,可以看作是MyClass的战略部分,我们希望将这部分独立出来,写成下面的方式:
public class Human
{
private string _name;
public string Name { get { return _name; } set { _name = value; } }
private int _age = -1;
public int Age { get { return _age; } set { _age = value; } }
private int _height = -1;
public int Height { get { return _height; } set { _height = value; } }
private int _weight = -1;
public int Weight { get { return _weight; } set { _weight = value; } }
public Human(string name, int age, int hight, int weight)
{
_name = name;
_age = age;
_height = hight;
_weight = weight;
}
}
//战略部接口
public interface Comparator
{
int compare(Human h1, Human h2);
}
public class AgeComparator : Comparator
{
public int compare(Human h1, Human h2)
{
if (h1.Age > h2.Age)
{
return 1;
}
else if (h1.Age == h2.Age)
{
return 0;
}
else
{
return -1;
}
}
}
public class HeightComparator : Comparator
{
public int compare(Human h1, Human h2)
{
if (h1.Height > h2.Height)
{
return 1;
}
else if (h1.Height == h2.Height)
{
return 0;
}
else
{
return -1;
}
}
public class MyClass
{
private Comparator comparator = null;
public MyClass(Comparator comparator)
{
this.comparator = comparator;
}
public int compare(Human h1, Human h2)
{
return comparator.compare(h1, h2);
}
}
class ProgramTest
{
static void Main(string[] args)
{
Human h1 = new Human("Tom", 21, 178, 60);
Human h2 = new Human("Jack", 22, 268, 56);
AgeComparator a = new AgeComparator();
MyClass m = new MyClass(a);
int i = m.compare(h1, h2);
Console.WriteLine("比较结果:" + i);
}
}
}
这样,比较接口始终一致,只要替换战略部分:重写接口Comparator,就能实现不同战略的比较。
没有评论:
发表评论