mercredi 30 novembre 2016

Pattern to avoid Cyclic calls

I have Policy class as below:

interface IPolicy
{
public:
virtual void func1() = 0;
}

class CPolicy : public IPolicy
{
public:
void func1() override { // do something }
}

And I have Utility Class as

class Util {
public:
void func1() {
if( policy != nullptr ) policy->func1(); // customized behavior

// default behavior
}

}

Now problem is, consider policy implementation have some condition and if that condition fails, policy calls default implementation ( this is one of the scenario, there can be multiple combinations )

class CPolicy : public IPolicy
{
public:
void func1() override { 
 if( condition ) 
 {
    // customized logic
 }
 pDefaultUtil->func1();
}
}

Now if you see this implementation it will endup in cyclic calls.

To solve such problem, I introduced another function in IPolicy contract.

interface IPolicy
{
public:
virtual void func1() = 0;
virtual bool ShouldUsePolicy() = 0;
}


class CPolicy : public IPolicy
{
public:
void func1() override { 
 if( condition ) 
 {
    // customized logic
 }
 usePolicy = false;
 pDefaultUtil->func1();
usePolicy = true;
// other logic continues.
}

bool ShouldUsePolicy() override { return usePolicy; }
private:
bool usePolicy { true };
}

and Util class is modified as :

class Util {
public:
void func1() {
if( policy != nullptr && policy->ShouldUsePolicy() ) policy->func1(); // customized behavior

// default behavior
}

}

With these changes, everything will work as expected, but I am not happy with this design. I don't want to depend on whether Policy is setting usePolicy variable properly or not. If any call comes from Policy to Default implementation then I should be able to ignore policy.

Is there any good pattern / solution for such problems?

Aucun commentaire:

Enregistrer un commentaire