zoukankan      html  css  js  c++  java
  • 使用继承健壮代码

    OOP不是简单的把函数和数据简单集合起来,而是使用类和继承轻松的描述现实中的情况。它可以通过继承复用代码,轻松升级项目。所以为了写出健壮可扩展的代码,通常需要尽量减少使用流程控制语句(比如if)

    <?php
    
    class Cat {
        function miao(){
            print "miao";
        }
    }
    
    class dog {
        function wuff(){
            print "wuff";
        }
    }
    
    function printTheRightSound($obj)
    {
        if ($obj instanceof cat) {
            $obj->miao();
        } elseif ($obj instanceof dog) {
            $obj->wuff();
        }
    }
    
    printTheRightSound(new Cat());
    printTheRightSound(new Dog());

    使用继承来优化

    <?php
    
    
    class Animal {
        function makeSound(){
            print "Error: This method should be re-implemented in the children";
        }
    }
    
    class Cat extends Animal {
        function makeSound(){
            print "miao";
        }
    }
    
    class Dog extends Animal{
        function makeSound(){
            print "wuff";
        }
    }
    
    function printTheRightSound($obj){
        if ($obj instanceof Animal) {
            $obj->makeSound();
        } else{
            print "Error:Passed wrong kind of object";
        }
        print "
    ";
    }
    
    printTheRightSound(new Cat());
    printTheRightSound(new Dog());
  • 相关阅读:
    继承和多态
    访问限制
    返回函数
    类和实例
    requests
    函数的参数
    代码块的快速放置
    19进阶、基于TSP的直流电机控制设计
    18进阶、TLC语言
    17高级、Simulink代码生成技术详解
  • 原文地址:https://www.cnblogs.com/ohmydenzi/p/8939303.html
Copyright © 2011-2022 走看看