Lets say I have a class that takes a delegate:
public class DelegateContainer
{
private IDelegate delegate;
public DelegateContainer(IDelegate delegate)
{
this.delegate = delegate;
}
public void doSomething()
{
delegate.doSomethingOnlyForThisPurpose();
}
{
As you can see the delegate's doSomethingOnlyForThisPurpose() method only exists to be called by the delegating class. However it is required that this method is public and could be executed by anything. If it absolutely shouldn't be executed by anything other than the delegating class it is attached to (especially if the delegating class passes in a dependency) then doesn't this break encapsulation? The only way I have thought to get around this is to contrive an object which can only be instantiated by the delegating class (inner class) which is passed to every method called. However, this is very convoluted and not watertight anyway. Is there any way around this or is it pathological?
Note: I want to stick with this compositional approach so I would rather not resort to inheritance.