vendredi 25 février 2022

Is it justifiable to implement Observer Pattern on Factory?

I have created a Factory by the name duckFactory which creates different Ducks from some Duck classes, now I want every time a duck is created the duckStore class must be notified. For this purpose, I created a DuckFactoryObserver interface which I implemented on the duckFactory class.

This is the Observer interface I created.

namespace App\interfaces\Observers;

interface DuckFactoryObserver {
    public function add( Duck $duck );

    public function notify();
}

This is where I Implemented the Observer pattern.

namespace App\Factories;
use App\Characters\MallardDuck;
use App\Characters\RubberDuck;
use App\Characters\DecoyDuck;
use App\interfaces\Observers\DuckFactoryObserver;

class DuckFactory implements DuckFactoryObserver {

    private $ducks = [];

    public function duckCreator( string $color, string $duckType ) {

        switch ( $duckType ) {
            case 'mallard':
            return new MallardDuck( $color, $duckType );
            break;
            case 'rubber':
            return new RubberDuck( $color, $duckType );
            break;
            case 'decoy':
            return new DecoyDuck( $color, $duckType );
            break;
            default:
            return 'No Duck of Such Type';
            break;
        }
    }

    public function add( Duck $duck ) {
        $this->ducks[] = $duck;
    }

    public function notify() {
        foreach ( $this->ducks as $duck ) {
            echo $duck->display();
        }
    }
}

My doubt is, is it a wise choice to implement one pattern on the other?

Aucun commentaire:

Enregistrer un commentaire