在一些C#代码中常常可以看到
- //An Simple Example By Ray Linn
- class CarCollection :ICollection
- {
- IList list;
- public void Add(Car car)
- {
- list.Add(car);
- }
- .... function list for ICollection...
- public void listPrice()
- {
- foreach(Car car in list)
- System.Console.WriteLin(car.Price);
- }
- ......more specifical function list...
- }
- class PetCollection :ICollection
- {
- IList list;
- public void Add(Pet pet)
- {
- list.Add(pet);
- }
- .... function list for ICollection...
- public void FeedPet()
- {
- foreach(Pet pet in list)
- System.Console.WriteLin(pet.Eating());
- }
- ......more specifical function list...
- }
这样的代码在很多Open Source项目中是很经常看到的,比如Cecil,其共同特点是:某种特定类型的Collection+该Collection特殊的操作,在一个项目中可能充斥着数十个类似的Collection,类似的代码在Java中很难被重构,但是在C#中,却可以借助扩展方法与范型进行代码的精减。
首先创建范型的Collection,该例子可以用List<T>来代替,但作为例子,我们假设该List<T>是特殊的(可能有一些delegate)
Java代码
- public CommonCollection<T>:ICollection<T>
- {
- IList<T> list
- .... function list for ICollection...
- }
- public CommonCollection<T>:ICollection<T>
- {
- IList<T> list
- .... function list for ICollection...
- }
对于Car和Pet的特殊操作,我们通过扩展方法来实现
- public static class CarExt
- {
- //Ext Function For CommonCollection<Car> by Ray Linn
- public static void listPrice(this CommonCollection<Car> collection)
- {
- foreach(Car car in collection)
- System.Console.WriteLin(car.Price);
- }
- ......more specifical function list...
- }
- public static class PetExt
- {
- //Ext Function For CommonCollection<Pet> by Ray Linn
- public static void FeedPet(this CommonCollection<Pet> collection)
- {
- foreach(Pet pet in list)
- System.Console.WriteLin(pet.Eating());
- }
- }
通过这样的方式,我们就实现了重构,两个Collection实现了求同存异。在我重构的Cecil之后,编译后的Assemly大小减小了一半.