0

Is there a difference between these two methods? If it is, which method is better?

First method. Using abstract class:

//Client class:
class Client extends Context
{
    public function insertData()
    {
        $this->chooseStrategy(new DataEntry());
        $this->algorithm();
    }
    public function findData()
    {
        $this->chooseStrategy(new SearchData());
        $this->algorithm();
    }
    public function showAll()
    {
        $this->chooseStrategy(new DisplayData());
        $this->algorithm();
    }
}
//Context class:
abstract class Context
{
    private $strategy;
    public function chooseStrategy(IStrategy $strategy)
    {
        $this->strategy = $strategy;
    }
    public function algorithm()
    {
        $this->strategy->algorithm();
    }
} 

Second method. Use simple class

//Client class:
class Client
{
    public function insertData()
    {
        $context = new Context(new DataEntry());
        $context->algorithm();
    }
    public function findData()
    {
        $context = new Context(new SearchData());
        $context->algorithm();
    }
    public function showAll()
    {
        $context = new Context(new DisplayData());
        $context->algorithm();
    }
}
//Context class:
class Context
{
    private $strategy;
    public function __construct(IStrategy $strategy)
    {
        $this->strategy = $strategy;
    }
    public function algorithm()
    {
        $this->strategy->algorithm();
    }
} 

Both methods use same IStrategy interface and same Strategy class.

l33tas
  • 33
  • 8

0 Answers0