1

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Willem, What should I do (change) to make it as a factory pattern ?
Willem, ok, so CreateNodeInstance called 'factory method' here ?
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.
0

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.

2 Comments

simple objects means objects that are not related to some other parts of a system, or other objects ?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.