¿Existe un patrón de diseño común para una clase principal que llama a varias de sus clases secundarias?

For example, I have several different merchant clients who I handle transactions for. They want different metrics for determining fraud, many of which are common. I'd like to have something to the effect of:

class Fraud
{

}

class InvalidCheckFraud extends Fraud
{

}

class NotAMemberFRaud extends Fraud
{

}

class CustomerLooksFunnyFraud extends Fraud
{

}

etc ...

I'd like to just be able to run zero to many extended Fraud classes using a command like:

$fraudCheck = new Fraud();
$fraudCheck->checkMerchant($merchId);

I don't mind solving this in a completely home grown fashion, but if it's already been figured out, I'd like to go that route.

I'm coding in PHP, but am fine with a reference using any other language.

preguntado el 08 de noviembre de 11 a las 18:11

2 Respuestas

Looks like you're looking for something like the Patrón de estrategia.

You should define an interface for your Fraud classes that accept a $merchId:

interface Fraud {
    public function check($merchId);
}

Then implement each subclass:

class InvalidCheckFraud implements Fraud {
    public function check($merchId) {
        // do something and return
        return true;
    }
}

class NotAMemberFraud implements Fraud
{
    public function check($merchId) {
        // do something and return
        return false;
    }
}

Then, create a context class that checks for each one:

class FraudContext implements Fraud {
    protected $_frauds = array();    

    public function addFraud(Fraud $fraud) {
        $this->_frauds[] = $fraud;
    }

    public function check($merchId) {
        foreach ($this->_frauds as $fraud) {
            if (!$fraud->check($merchId)) {
                throw new LogicException(
                  "{$merchId} has failed the check for ".get_class($fraud)
                );
            }
        }
        return true;
    }
}

$merchId = 42;
$context = new FraudContext;
$context->addFraud(new InvalidCheckFraud);
$context->addFraud(new NotAMemberFRaud);
$context->check($merchId);

respondido 08 nov., 11:23

Thanks, that FraudContext method is kind of what I was looking for, I've found a pattern called the Chain-of-responsibility pattern, I think a combination of this and your answer is what I'm looking for. - Parris Varney

@PMV: Yes, exactly. My example is actually a combination of Strategy and C-o-R patterns. C-o-R can actually be considered an implementation of Strategy. - netcoder

Your Fraud class should be called FraudChecker or something similar and have a list of Fraud subclasses that it can check, or classes implementing some interface. You then just loop over each check.

respondido 08 nov., 11:22

Autocorrection? But I like the fact that a class can have sunglasses :) editar: you cannot hide it from me ;) - Felix Kling

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.