c# - combine and intercept methods of 2 classes defined by same interface -
i have series of classes implement interface. want create 3rd class (that implements interface) combines methods of both classes single one, plus add managing code. in other words.
let's have interface:
public interface itestclass {     string namepluslastname(string name);      int ageplus20(int age);      datetime yearyouwilldie(int age); }   and have these 2 classes implement it:
public class testclasspeter : itestclass {     public string namepluslastname(string name)     {         return string.concat(name, " ", "mc.cormick");     }      public int ageplus20(int age)     {         return age + 40;     }      public datetime yearyouwilldie(int age)     {         return datetime.now;     } }  public class testclasscharles : itestclass {     public string namepluslastname(string name)     {         return string.concat(name, " ", "gonzales");     }      public int ageplus20(int age)     {         return age + 20;     }      public datetime yearyouwilldie(int age)     {         return datetime.now ;     } }   i want create class returns object implements itestclass , methods combination of both classes. such as:
public class testboth  {     itestclass peter;     itestclass charles;     itestclass combinedclass;      public testboth()     {         // instantiate classes combined.         peter = new testclasspeter();         charles = new testclasscharles();          // beg         // add here code automatically combine methods of both classes one.         // ......         // end      }      // expose property     public itestclass combinedclass     {                 {             return combinedclass;         }     } }   so in end can call combined class this:
testboth classbuilder = new testboth(); itestclass combinedclass = classbuilder.combinedclass;  // call method string fullname = combinedclass.namepluslastname("william");   and going on behind scenes really:
string firstvalue = peter.namepluslastname("william"); // code here string secondvalue = charles.namepluslastname("william"); // more code here return finalvalue;   i want happen automatically methods. way, if change interface definition, , implementation of peter , charles, automatically modified in classbuilder.
sounds might want use decorator pattern. here example of how works.
Comments
Post a Comment