// Iterator class public class MyIterator { protected IVisitor Visitor; public void RegisterVisitor(IVisitor visit) { this.Visitor = visit; } } // Visitor class public class MyVisitor : IVisitor { public bool Process(string s) { MessageBox.Show(s); return true; } } // IVisitor interface public interface IVisitor { bool Process(string s); }Here's some code that instantiates the iterator and visitor, then calls the RegisterVisitor method.
public class TestComposition { public void Test() { // Instantiate the iterator MyIterator iterator = new MyIterator(); // Instantiate the visitor MyVisitor visitor = new MyVisitor(); // Register the visitor with the iterator iterator.RegisterVisitor(visitor); } }You can also factor this down as follows:
// Instantiate the iterator MyIterator iterator = new MyIterator(); // Register the visitor with the iterator iterator.RegisterVisitor(new MyVisitor());Going further with the example, you could give the iterator a constructor that accepts an IVisitor parameter:
// Iterator class public class MyIterator { protected IVisitor Visitor; public MyIterator(IVisitor visit) { this.RegisterVisitor(visit); } public void RegisterVisitor(IVisitor visit) { this.Visitor = visit; } }You could then do the whole instantiation and registration process in a single line:
MyIterator iterator = new MyIterator(new MyVisitor());If you want to create an aggregation relationship where one object is the owner of another, you could do much the same thing, except the owner object might instantiate the Aggregatee. If you go this route, I highly recommend instantiating the Aggregatee in a factory method. For example, the following code shows the Business Object class (the owner, or Aggregator) instantiating a Business Rule object (the Aggregatee) in its constructor by calling a factory method named CreateBusinessRulesObject(). Creating aggregate objects this way allows subclasses to override the factory method and instantiate a different Aggregatee.
// Business Object class public class BusinessObject { protected BusinessRules MyBizRules; // Constructor public BusinessObject() { this.CreateBusinessRulesObject(); } // Factory method public void CreateBusinessRulesObject() { this.MyBizRules = new BusinessRules(); } } // Business Rule class public class BusinessRules { }Hope this helps!