mercredi 14 juin 2023

Two different implementations only for some methods of the same in class .NET (design pattern)

I have one class with many methods. I need to have two different implementations of two methods within class, but all other methods should be the same.

public class MyDataService: IMyDataService
{
       public void Method1() { // get data from external service } 
       public void Method2() { // get data from external service } 

       public void CommonMethodA() { // some get data} 
       public void CommonMethodB() { // some get data } 
       public void CommonMethodC() { // some get data }
        ... and other methods here 
}

IMyService is injected in Startup. In another layer we use these methods.

public class MyManager {

       public void DoComplexCalculations() {
            _myservice.CommonMethodA();

            _myservice.CommonMethodB();

            _myservice.Method1();
       }
}

public class Caculator1() {
     public void Do() { _mymanager.DoComplexCalculations(); }
}

However, now we have developed another application (in .net it is separate project within the same solution), it also calls MyManager.DoComplexCalculations.

public class Caculator2() {
    // we need to call the same calculations, but need different Metohd1 and Method2
    public void Do() { _mymanager.DoComplexCalculations(); }
}

Instead of calling Method1 and Method2 we need to get data form Cache (call FromCacheMethod1 and call FromCacheMethod2 ). All other methods are common and are still needed. Data are already cached before calling MyManager.DoComplexCalculations. What is best approach to achieve this?

  1. Using Decorator pattern, but in this case we should create a lot of unneeded code, just duplicating CommonMethodX calls in decorator class. And it doesn't sound actually like Decorator.

  2. Or add get from cache code inside Mehtod1 and Method2, but this also doesn't sound as good pattern.

Aucun commentaire:

Enregistrer un commentaire