Code neat way - and the object data structure

Now, there is a need to calculate the area, in which one implementation is as follows:

class Square{
    public $side;
}
class Geometry{
    public function area($shape){
        if($shape instanceof Square){
            return $shape->side * $shape->side;
        }
        return 0;
    }
}

 

Someone saw you this abstract problem ah, obviously is process-oriented, if you add a new type, all methods Geometry class to be modified. Ah, but it is so, but the other way round, if you add a new method, all existing shapes classes do not move, just add methods in Geometry class on the line.

Of course, there is a multi-state implementation:

class Square implements Shape{
    private $side;
    public function area(){
        return $this->side * $this->side;
    }
}

 

Do you think so everything will be fine? not at all. Indeed achieved, add a new type, as long as the new shoe a class that implements the method can be very simple. But if you want to add a new function, that I am sorry, all classes must be modified.

Under a brief summary, that:

  • Procedural code is easy to add new functions without modifying the data structure is composed of the premise, the object is not easy to change the current oriented to add a new type of function provided by the
  • Procedural code is difficult to add a new data structure, since it is necessary to modify all functions. Object-oriented code is difficult to add a new function, since it is necessary to modify all the classes
  • The behavior of objects exposed, hidden data. Easy to add new data type without having to modify existing behavior, but also it is difficult to add new behavior in existing object
  • A data structure (to achieve the above first) exposure data, no significant behavior. Easy to add new behavior to an existing data structure, and also difficult to add a new function to an existing data structure.

Of course, what kind of specific use or should the flexibility to choose, not rigidly stick.

If you want the flexibility to add new behavior, it uses data structures. If you want the flexibility to add new types, on the use of object-oriented approach.

Guess you like

Origin www.cnblogs.com/hujingnb/p/11568721.html