N
N
NikolayAlb2017-03-03 01:24:59
Design patterns
NikolayAlb, 2017-03-03 01:24:59

What is the difference between Strategy and Builder patterns?

The builder is essentially a set of predefined algorithms with a common interface that the "director" uses, the director receives a builder and uses it to create/modify some kind of object.
The strategy is also essentially a set of predefined algorithms with a common interface that the "context" uses, the context receives the algorithm and performs certain operations with its help.
So what's the conceptual difference? Even their diagrams are almost identical. The only thing that I could note myself is that the builder composes and returns the .
I would like an answer with examples.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2017-03-03
@NikolayAlb

essentially a set of predefined algorithms with a common interface

There are too many things in the world of programming that can be described that way. Therefore, you should not use this criterion at all to assess the similarity of patterns. The difference between all the patterns lies in their purpose, that is, what task this or that pattern solves and what area of ​​responsibility it has.
Let's take a builder as an example:
class Builder {

  protected $obj;

  public function create(){
    $this->obj = new HtmlDocument();
  }
  
  public function addHeader(){
    // добавляем хедер в $this->obj
  }
  
  public function addFooter(){
    // добавляем футер в $this->obj
  }
  
  public function getObj(){
    return $this->obj;
  }
}

What is the purpose of a builder? Creating a complex object and providing an interface for its configuration. At the same time, the builder object does not have information about how it will be configured in a specific situation - this is the task of the classes using it.
Now let's take a strategy:
interface CalculateDiscountInterface {

  public function execute($price);
}

class ClientCalculateDiscount implements CalculateDiscountInterface {

  public function execute($price){
    // рассчитываем цену по одному алгоритму
  }
}

class ParterCalculateDiscount implements CalculateDiscountInterface {

  public function execute($price){
    // рассчитываем цену по другому алгоритму
  }
}

What is the purpose of the strategy? Implementation of the same functionality using different algorithms, with the possibility of replacing each other.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question