Delegates: Difference between revisions

Content deleted Content added
m moved Delegate to Delegates
No edit summary
Line 158: Line 158:
Delegator_Operation( theDelegator, 3, del2));
Delegator_Operation( theDelegator, 3, del2));
return 0;
return 0;
}</lang>

=={{header|C++}}==
<lang Cpp>#include <boost/shared_ptr.hpp>
#include <string>
#include <iostream>

// interface
class IDelegate
{
public:
virtual std::string Thing()
{
return "default implementation";
}

protected:
IDelegate() {}
};

// Does not handle Thing
class DelegateA : public IDelegate
{
};

// Handles Thing
class DelegateB : public IDelegate
{
std::string Thing()
{
return "delegate implementation";
}
};

class Delegator
{
public:
std::string Operation()
{
if(Delegate)
return Delegate->Thing();
else
return "no implementation";
}

boost::shared_ptr<IDelegate> Delegate;
};

int main()
{
boost::shared_ptr<DelegateA> delegateA(new DelegateA());
boost::shared_ptr<DelegateB> delegateB(new DelegateB());
Delegator delegator;

// No delegate
std::cout << delegator.Operation() << std::endl;

// Delegate doesn't handle "Thing"
delegator.Delegate = delegateA;
std::cout << delegator.Operation() << std::endl;

// Delegate handles "Thing"
delegator.Delegate = delegateB;
std::cout << delegator.Operation() << std::endl;
}</lang>
}</lang>