简体   繁体   中英

How do I create Optional Type injection for a base class?

During the course of regular Agile programming technique, I often do a lot of refactoring. If I find common things they are candidates for a base class. Assume this code pattern:

public Subclass : BaseClass{
   private dynamic SomeValue = null;
   public Subclass(){
       SomeValue = BaseClass.Method<T>();
   }
}

Everything works fine until I get tired of continually injecting the type into the method. Why not inject the type into the base class instead? But wait a second, I don't want to have to redo 20 classes already using this pattern above. Now I have two potential patterns I can use, this being the second.

public Subclass : BaseClass<T>{
   private T SomeValue = null;
   public Subclass(){
       SomeValue = BaseClass.Method();
   }
}

This second pattern could be a logical derivation of the first example whereby we are merely moving the type to the class CTOR instead of using the generic type in each method.

I would like to ask the community their thoughts on how to accomplish both constructs without changing any current code but adding in support of the generic type baseclass pattern.

Once again the Gang of Four was right "Favor Composition over inheritance". In this case maybe the term BaseClass is not appropriate, but you can see how our baseclass concept was just wrong at the beginning by not really asking "is this really a Baseclass?"

public Subclass {
   private BaseClass bc1 = null;
   private BaseClass<SomeType> bc2 = null;
   private dynamic SomeValue = null;
   public Subclass(){
     //I still have base class operation ability, but now...
     bc2 = new BaseClass<SomeType>();
     SomeValue = bc2.Method();
 }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM