Как реализовать проблему интерфейса класса куриного яйца в php - PullRequest
0 голосов
/ 19 сентября 2018

Я получил следующий вызов кода.Речь идет об интерфейсе, наследовании классов и т. Д. Не знал, как это сделать.Вот что я получил

// interface bird
interface Bird
{
    // lay egg
    public function layEgg();
}

// chicken can lay egg
class Chicken implements Bird
{
    public function layEgg() {
        return new Egg();
    }
}

// class egg
class Egg
{
    public $count=0;

    // egg, bird type
    public function __construct($birdType)
    {

    }

    // hatch, born chick
    public function hatch()
    {
        if($this->count == 0)
            $this->count++;

        if($this->count == 1)
             throw new Exception('lay egg for 2nd time');
    }
}

Есть 4 требования: Курица реализует интерфейс птицы.

Курица откладывает куриное яйцо.

Различные типы птиц откладывают разные яйца, соответственно.

Люк дважды выдаст исключение.

Есть идеи?

Ответы [ 3 ]

0 голосов
/ 19 апреля 2019

Вот моя попытка с некоторыми дополнениями:

interface Bird{
// lay egg
   public function layEgg();
   public function printType();
}

 // chicken can lay egg
class Chicken implements Bird{
    public $counter = 0;
    public function layEgg() {
        $this->counter++;
        $egg= new Egg($this);
        return $egg;

    }
    public function printType(){
        echo get_class($this)." egg is layed";
    }
    public function printDescandantNumber(){
        echo $this->counter;
    }
}


// Eagle can lay egg
class Eagle implements Bird{
    public $counter = 0;
    public function layEgg() {
        $this->counter++;
        $egg= new Egg($this);
        return $egg;

    }
    public function printType(){
        echo get_class($this)." egg is layed";
    }
    public function printDescandantNumber(){
        echo $this->counter;
    }
}

// class egg
class Egg {
    public $count=0;
    private $birdtype;
    private $generation;

    // egg, bird type
    public function __construct($birdType){
        $this->birdtype=$birdType;
        $this->generation=$this->birdtype->counter++;
    }

    // hatch, born chick
    public function hatch(){

        if($this->count == 0){
            $this->count++;
            $bird = new $this->birdtype;
            $bird->counter=$this->generation;
            return $bird;
        }


        if($this->count == 1)
            throw new Exception('lay egg for 2nd time');
   }
}
0 голосов
/ 07 июня 2019

Вот решение, которое работает на 100%, для одного из моих интервью, которое я использовал, Testdome надеюсь, что оно кому-нибудь поможет.Но, пожалуйста, не просто копируйте и вставляйте для своего потенциального работодателя, пожалуйста, тратьте больше времени и понимайте проблему и решение, вопрос выглядит трудным, но ответ прост

{
    public function layEgg();
}

class Chicken implements Bird
{
    public $egg = null;
    public $eggnum;
    public function layEgg() {
        $this->egg = new Egg(self::class);
        echo "This is the egg";
        return $this->egg;
    }
}

class Egg
{
    public $birdType;
    protected $is_hatched = false;
    public function __construct($birdType)
    {
        $this->birdType = $birdType;
    }

    public function hatch()
    {
        if ($this->is_hatched){
            // throws
            throw new Exception('lay egg for 2nd time');
        }
        $bird_type = $this->birdType;
        $bird = new $bird_type();
        if (!($bird instanceof Bird)){
            // throws
        }

        $this->is_hatched = true;
        echo "I have hatched";
        return $bird;
    }
}
0 голосов
/ 19 сентября 2018

Вот моя попытка:

interface BirdInterface
{
    public function layEgg(): AbstractEgg;
}

abstract class AbstractEgg
{
    /**
     * @var BirdInterface|null
     */
    protected $hatchedBird = null;

    protected function hatchCheck() {
        if (!is_null($this->hatchedBird)) {
            throw new \Exception();
        }
    }
}

class Chicken implements BirdInterface
{
    public function layEgg(): AbstractEgg
    {
        return new ChickenEgg();
    }
}

class ChickenEgg extends AbstractEgg
{
    public function hatch(): BirdInterface
    {
        $this->hatchCheck();
        return $this->hatchedBird = new Chicken();
    }
}

https://www.php -fig.org / bylaws / psr-naming-Conventions /

Обновлено с более абстрактной версией.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...