委托模式;如何共享上下文信息?

时间:2019-11-02 12:31:33

标签: design-patterns architecture software-design delegation

对于委派的设计模式的好与坏做法,我有些困惑。 也许我的整个概念走错了方向。所以我需要一些建议和指导!

我用简单的设置写了一些示例代码来显示我的问题。我希望尽可能将ITaskDistributor与ITaskDistributor分离。但是最后我看到了将它紧密结合起来的需求。我对此感到非常难过,不确定该怎么办。

// 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

}

我如何实现,TaskSpecial对执行它的人足够了解,因此它仍然可以工作,但是要尽可能地分离。 尽管我的代码是用C#编写的,但我对设计模式的误解并非特定于语言。

0 个答案:

没有答案