zoukankan      html  css  js  c++  java
  • 设计模式(二)----工厂模式

    工厂模式是我们最常用的实例化对象模式了,是用工厂方法代替new操作的一种模式。

    工厂模式会是我们的应用获取更多的可扩展性,减少修改量.

    <?php

    Interface Animal

    {
      public function food();
    }
    class Cat implements Animal
    {
      public function food()
    {
      echo "小猫吃小鱼";
    }
    }
    class Fish implements Animal
    {
      public function food(){

      echo "小鱼吃虾米";

      }
    }
    Class Shrimp implements Animal
    {
      public function food(){
      echo "我吃什么";
      }
    }

    class animalFactory
    {
      public static function factory($animal)
      {
        // $animal = ucfirst($animal);
        switch ($animal){
          case "cat":
            return new Cat();
            break;
          case "dog":
            return new Fish();
            break;
          case "shrimp":
            return new Cat();
            break;
        }
      }
    }

    try{
      $animal = animalFactory::factory('dog');
      throw new Exception("可能你输入错误了吧");
      }catch(Exception $e){
        echo "错误信息是:" . $e->getMessage();die;
    }
    $animal->food();

  • 相关阅读:
    Lyndon Word & The Runs Theorem
    Codeforces 1477F. Nezzar and Chocolate Bars
    Codeforces Round #700 (Div.1)
    kubeadm 安装 k8s
    centos7更新阿里yum源
    CF1186 F. Vus the Cossack and a Graph
    CF1152 D. Neko and Aki's Prank
    CF803 C. Maximal GCD
    CF1180 B. Nick and Array
    CF1186 D. Vus the Cossack and Numbers
  • 原文地址:https://www.cnblogs.com/catcrazy/p/6289379.html
Copyright © 2011-2022 走看看