Better solution then simple factory method when concrete implementations have different attributes

Posted by danip on Programmers See other posts from Programmers or by danip
Published on 2013-06-30T16:08:54Z Indexed on 2013/06/30 16:27 UTC
Read the original article Hit count: 318

abstract class Animal {
  function eat() {..}
  function sleep() {..}
  function isSmart()
}

class Dog extends Animal {
  public $blnCanBark;
  function isSmart() {
    return $this->blnCanBark;
  }
}

class Cat extends Animal {
  public $blnCanJumpHigh;
  function isSmart() {
    return $this->blnCanJumpHigh;
  }
}

.. and so on up to 10-20 animals.

Now I created a factory using simple factory method and try to create instances like this:

class AnimalFactory {
  public static function create($strName) {
       switch($strName) {
          case 'Dog':
            return new Dog();
          case 'Cat':
            return new Cat();
          default:
            break;
       }
  }
}

The problem is I can't set the specific attributes like blnCanBark, blnCanJumpHigh in an efficient way.

I can send all of them as extra params to create but this will not scale to more then a few classes. Also I can't break the inheritance because a lot of the basic functionality is the same.

Is there a better pattern to solve this?

© Programmers or respective owner

Related posts about php

Related posts about design-patterns