Delegates: Difference between revisions

no edit summary
No edit summary
No edit summary
Line 189:
 
=={{header|C++}}==
Delegates in the C# or D style are available in C++ through std::tr1::function class template. These delegates don't exactly match this problem statement though, as they only support a single method call (which is operator()), and so don't support querying for support of particular methods.
<lang Cpp>#include <boost/shared_ptr.hpp>
 
}</lang Cpp>
#include <tr1/memory>
#include <string>
#include <iostream>
#include <tr1/functional>
 
using namespace std;
using namespace std::tr1;
using std::tr1::function;
 
// interface for all delegates
class IDelegate
{
public:
virtual std::string Thing~IDelegate() {}
};
{
return "default implementation";
}
 
//interface for delegates supporting thing
protected:
class IThing
IDelegate() {}
{
public:
virtual ~IThing() {}
virtual std::string Thing() = 0;
};
 
// Does not handle Thing
class DelegateA : virtual public IDelegate
{
};
 
// Handles Thing
class DelegateB : public IThing, public IDelegate
{
std::string Thing()
Line 219 ⟶ 229:
}
};
 
class Delegator
{
Line 225 ⟶ 235:
std::string Operation()
{
if(Delegate) //have delegate
if return(IThing Delegate-* pThing = dynamic_cast<IThing*>Thing(Delegate.get()));
//delegate provides IThing interface
else
return "no implementation"pThing->Thing();
{
return "default 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>
 
/*
Prints:
 
default implementation
default implementation
delegate implementation
*/
}
</lang>
=={{header|Common Lisp}}==
{{trans|Python}}
Anonymous user