views:

91

answers:

2

What is a name of that pattern ? I guess, it's a factory, but i am not sure.

using System.Windows.Forms;

    public class TreeNodeHelper
    {
        public TreeNode GetTreeNodeType1()
        {
            return new TreeNode("type1");
        }

        public TreeNode GetTreeNodeType2()
        {
            return new TreeNode("type2");
        }

        // etc
    }

TreeNodeHelper class returns different instances of TreeNode. It only returns TreeNodes instances and nothing else.

A: 

It creates and returns objects, so it's some variant of a Factory or Builder. Since it returns simple objects, and not complex ones, it's a Factory variant.

kyoryu
simple objects means objects that are not related to some other parts of a system, or other objects ?
nik
Not composite objects that have dependencies... the point being that it is creating single, relatively simple objects, not constructing and building complex objects in different ways based on parameters passed... that'd be more like a Builder.
kyoryu
+1  A: 

It's a factory of kinds, but not the factory pattern.

Also note that the factory pattern(or variants), usually only have one method, with one (or more) parameter(s) with which it can decide for which type to create an instance, not two (or more) methods.

I would also rename the methods to something like "CreateNodeInstance" or something similar. You're creating and returning instances, not retrieving types.

Edit

Without knowing your requirements completely, a simple modification would be something along the lines of

static public class TreeNodeHelper
{
    static public TreeNode CreateNodeInstance(criterion)
    {
         if (criterion == xyz)
         {
             return new XyzTreeNode();
         }
         else if (criterion == foo)
         {
             return new FooTreeNode();
         }
         else if (etc...etc...
    }
}

This would be an implementation of the factory method pattern, not the abstract factory pattern. The latter link also contains an example in C#, but I doubt if you will need the full abstract factory implementation.

Willem van Rumpt
Willem, What should I do (change) to make it as a factory pattern ?
nik
@nik: Updated the answer
Willem van Rumpt
Willem, ok, so CreateNodeInstance called 'factory method' here ?
nik
Correct. The factories in the abstract factory pattern also have factory methods, but the main difference is that that pattern allows to completely swap in different factories all together.
Willem van Rumpt