samedi 2 novembre 2019

Delegation Pattern; How to share contextual information?

I'm a bit confused about good and bad practices concerning the design pattern of delegation. Maybe my whole concept went in the wrong direction. So i need some advice and some mentoring!

I wrote some example code with a simple setup which shows my problem. There is the delegation type ITask which i want to have as decoupled as much as possible form ITaskDistributor. But in the end i saw the need arising to couple it a bit more tightly. I feel very bad about that and am not sure what to do.

// Generic ParameterSet as interface for all objects involved in working with the tasks
public interface ITaskDistributor{
 IParameterSet Parameters{ get; }
}

// Executeing some specific code in reading/writing the ParameterSets of processor and distributor
public interface ITask{
 void Execute( IDataSet dataset, ITaskDistributor distributor );
}

public interface IDataSet : TaskDistributor{
 //... specific members and methods - mostly variables
}

public class TaskDistributorAlpha : ITaskDistributor{
 //...
 private List<IDataSet> datasets = new List<IDataSet>();
 void Run( ITask task ){
  foreach( var ds in datasets )
   task.Execute( ds, this ); //do some stuff with DataSet and own ParameterSet
 }
}


public class TaskRegular : ITask{
 public void Execute( IDataSet dataset, ITaskDistributor distributor ){
   //everything fine
 }
}

public class TaskSpecial : ITask{
 public void Execute( IDataSet dataset, ITaskDistributor distributor ){
  //want to access BetaOnlyParameters which is specific to TaskDistributorBeta and not to 
 }
}

public class TaskDistributorBeta : ITaskDistributor{
 //... similar to Alpha 
 IParameterSet BetaOnlyParamters{ get; }
}




public void main(){
 var alpha = new TaskDistributorAlpha();
 alpha.Run( new TaskRegular() ); //everything fine

 var beta = new TaskDistributorBeta();
 beta.Run( new TaskRegular() ); //still everything fine

 var dataset = new DataSetImplementationNotShownHere();
 dataset.RunATask( new TaskRegular() ); //works fine because IDataSet is also interfaced - nice to have but not absolutely necessary.

 beta.Run( new TaskSpecial() ); //i want it to be more coupled but i feel bad about it and dont know what to do with that

}

How can i achieve, that TaskSpecial knows enough about the one executing it that it stills works but is as decoupled as possible. Although my code is in c# my possible misunderstanding of the design pattern is not language specific.

Aucun commentaire:

Enregistrer un commentaire