1
- 需求:人 扔手雷、飞镖等等。。。。
- 变化点:扔的对象
-
方法:
3.1.png
public class Person
{
public void Throw(IThrowable iThrow)
{
iThrow.Throw();
}
}
public interface IThrowable
{
void Throw();
}
public class Grenade : IThrowable
{
public void Throw()
{
Console.WriteLine("扔手雷");
}
}
public class Darts : IThrowable
{
public void Throw()
{
Console.WriteLine("扔飞镖");
}
}
static void Main(string[] args)
{
Person per = new Person();
// 扔手雷
per.Throw(new Grenade());
// 扔飞镖
per.Throw(new Darts());
}
}
- 分析:设计思想与使用抽象类一致,使用接口将人与手雷、飞镖等具体对象隔离。
2
- 需求:对手雷数组进行排序
- 方法:
public class Grenade : IThrowable, IComparable
{
public int ATK { get; set; }
public int AttackDistance { get; set; }
public int CompareTo(object obj)
{
return this.ATK.CompareTo((obj as Grenade).ATK);
}
public void Throw()
{
Console.WriteLine("扔手雷");
}
}
public class GrenadeComparer : IComparer<Grenade>
{
public int Compare([AllowNull] Grenade x, [AllowNull] Grenade y)
{
return x.AttackDistance.CompareTo(y.AttackDistance);
}
}
static void Main(string[] args)
{
Grenade[] grenadeArray = new Grenade[3]
{
new Grenade(){ATK = 10, AttackDistance = 5},
new Grenade(){ATK = 5, AttackDistance = 10},
new Grenade(){ATK = 7, AttackDistance = 6}
};
// sort1
Array.Sort(grenadeArray);
// sort2
Array.Sort(grenadeArray, new GrenadeComparer());
}
- 分析:方法1将Grenade继承自IComparable接口,并在内部实现其对应的CompareTo方法。最后使用Array.Sort(grenadeArray)进行排序。该方法适用与对象使用默认属性进行排序,若需要按别的属性进行排序,需修改类本身,不满足开闭原则。
方法2将比较方法抽象为GrenadeComparer,继承自接口IComparer,然后实现其Compare方法,最后交给Array.Sort进行排序。当需要修改排序属性时,只需修改GrenadeComparer即可。
当然,也可以通过属性名称进行动态变化,这里不做讨论。
3
- 需求:自定义冒泡排序算法
- 方法:
// 冒泡排序
// 变化点: 类型 依据
// 解决: 泛型 委托
private static void MySort<T>(T[] array, Func<T, T, bool> handler)
{
for (int i = 0; i < array.Length - 1; i++)
{
for (int j = i + 1; j < array.Length; j++)
{
if (handler(array[i], array[j]))
{
T tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
}
}
- 分析:排序的变化点为类型和依据。在本算法中,使用泛型解决类型变化,使用委托解决依据变化。
4
总结:
// 抽象类:一个概念的抽象(普通成员、抽象成员)
// 接口:一组行为的抽象(多种抽象成员,无法包含字段)
// 委托:一类行为的抽象(同一种类别)
