Search code examples
c#design-patternstreeflyweight-pattern

C# Processing same object with different "processors" a flyweight pattern?


I've been doing a lot of research on different design patterns and I'm trying to determine the correct way of doing this.

I have an image uploading MVC app that I'm developing which needs to process the image in several different ways, such as create a thumbnail and save a database record. Would the best way to approach this be via a flyweight pattern? Using this as an example:

var image = new Image();    

List<IProcessors> processors = processorFactory.GetProcessors(ImageType.Jpeg);

foreach(IProcessor processor in processors)
{
    processor.process(image);
}

I have second part to this question as well. What if the processor has smaller related "sub-processors"? An example that I have in my head would be a book generator.

I have a book generator 
     that has page generators
          that has paragraph generators
               that has sentence generators

Would this be a flyweight pattern as well? How would I handle the traversal of that tree?

EDIT

I asked this question below but I wanted to add it here:

All the examples that I've see of the composite pattern seems to relate to handling of values while the flyweight pattern seems to deal with processing (or sharing) of an object's state. Am I just reading into the examples too much? Would combining the patterns be the solution?


Solution

  • I can at least handle the second part of the question. To expand a tree (or a composite), use simple recursion.

    void Recursion(TreeItem parent) 
    {
        // First call the same function for all the children.
        // This will take us all the way to the bottom of the tree.
        // The foreach loop won't execute when we're at the bottom.
        foreach (TreeItem child in parent.Children) 
        {
             Recursion(child);
        }
        
        // When there are no more children (since we're at the bottom)
        // then finally perform the task you want. This will slowly work
        // it's way up the entire tree from bottom most items to the top.
        Console.WriteLine(parent.Name);
    }