Delegates: Difference between revisions

Content deleted Content added
No edit summary
No edit summary
Line 189: Line 189:


=={{header|C++}}==
=={{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 <string>
#include <iostream>
#include <iostream>
#include <tr1/functional>

using namespace std;
using namespace std::tr1;
using std::tr1::function;


// interface
// interface for all delegates
class IDelegate
class IDelegate
{
{
public:
public:
virtual std::string Thing()
virtual ~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
// Does not handle Thing
class DelegateA : public IDelegate
class DelegateA : virtual public IDelegate
{
{
};
};

// Handles Thing
// Handles Thing
class DelegateB : public IDelegate
class DelegateB : public IThing, public IDelegate
{
{
std::string Thing()
std::string Thing()
Line 219: Line 229:
}
}
};
};

class Delegator
class Delegator
{
{
Line 225: Line 235:
std::string Operation()
std::string Operation()
{
{
if(Delegate)
if(Delegate) //have delegate
return Delegate->Thing();
if (IThing * pThing = dynamic_cast<IThing*>(Delegate.get()))
//delegate provides IThing interface
else
return "no implementation";
return pThing->Thing();
return "default implementation";
}
}

boost::shared_ptr<IDelegate> Delegate;
shared_ptr<IDelegate> Delegate;
};
};

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

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

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

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


/*
Prints:

default implementation
default implementation
delegate implementation
*/
}
</lang>
=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
{{trans|Python}}
{{trans|Python}}