views:

86

answers:

2

Hi there, i want to create an abstract representation of an existing object. For this example i want to wrap the functionality of a System.Windows.Forms.TreeNode. I started by creating an adapter as follows...

Edit : The purpose of the abstraction will allow me to use the ITreeNodeAdapter in my application without knowing about the TreeNode, at a later stage I could implement a different ITreeNodeAdapter and the application would still work. I basically want to remove dependency on the TreeNode.

public interface ITreeNodeAdapter
{
    string Title {get;set;}
    void Add(ITreeNodeAdapter adapter);
}

public class TreeNodeAdapter : ITreeNodeAdapter
{    
    public AbstractTreeNode(TreeNode node)
    {
        this.Node = node;
    }

    private TreeNode Node {get;set;}

    public string Title
    {
        get { return _node.Text; }
        set { _node.Text = value; }
    }

    public void Add(ITreeNodeAdapter adapter)
    {
        // What should i do here?
        var treeNodeAdapter = adapter as TreeNodeAdapter;
        if(treeNodeAdapter != null)
        {
            this.Node.Nodes.Add(treeNodeAdapter.Node);
        }
    }
}

I am having problems with extending the class to accept child nodes... the approach i have used above doesn't feel very nice. Any idea how i could improve?

A: 
  1. Change your interface name to ITreeNode or something like that. You are creating an abstraction with the interface. An adapter is what takes one implementation and makes it look like a desired abstraction

  2. Where are you having problems adding children? Add a method to the ITreeNode interface you defined and then implement it in the adapter.

tster
Any chance you could provide an example?
Rohan West
+1  A: 

You could use the Abstract factory pattern.

In case you might wonder it's not limited to new object, you can use it to existing objects.

call me Steve