Recommended design pattern(s) to use [closed]

你。 提交于 2020-01-06 08:00:54

问题


Suppose I have very basic Task class as follows:

public class Task
{
    string Title { get; set; }
}

Now I want to add Planning "behaviour" to SOME of my tasks. Obviously I will have to have something like:

public interface IPlannable
{
    public void CalculatePlan();
    public DateTime Start { get; }
    public DateTime Finish { get; }
}

and two concrete algorithms, each with different input parameters:

public class PlanStrategyA : IPlannable
{
    private int parameter1;
    private int parameter2;
    private DateTime start;
    private DateTime finish;

    public PlanStrategyA(int p1, int p2)
    {
        parameter1 = p1;
        parameter2 = p2;
    }

    public void CalculatePlan()
    {
        // ... uses parameter1 & parameter2
        // ... to calculate start and finish
    }

    public DateTime Start { get { return this.start; } }

    public DateTime Finish { get { return this.finish; } }
}

public class PlanStrategyB : IPlannable
{
    public int parameter3;

    // ... the rest is similar to PlanningStrategyA

}

Question is :

What is best design pattern to use to connect base Task class to concrete Planning strategy as OPTION, meaning that not all Tasks is required to be planned, ie. to have Planning behaviour ?

User should have possibility to "promote" task to be planned, and also to "remove" this behaviour from particular task.

How all this applies to persisting to Database via EF, or other ORM, particularly when reading from database ? What pattern will best fit reading from DB and creating back my task objects ?


回答1:


Seems that you have 2 distinct issues here. One is the strategy algorithm for plannable tasks - you can use a Strategy pattern for handling this. Regarding the tasks that aren't plannable, I see 2 possible approaches:

  1. Exclude it from scope of design pattern. It's perfectly ok, patterns shouldn't be forced upon your design if not needed.
  2. Have a 2-level strategy - upper level to choose whether task is plannable or not and lower level (for plannable only) to apply your strategy.

The other one is a set of possible behaviors for each task. This can be tackled with Composite pattern. No behavior is also a behavior.



来源:https://stackoverflow.com/questions/13503015/recommended-design-patterns-to-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!