工厂模式创建工厂类

原创 2018-12-20 17:15:09 196
摘要: <?php class Person {     public function work()     {         return '可以挣钱';   
<?php
class Person
{
    public function work()
    {
        return '可以挣钱';
    }
}

class Mechine
{
    public function run()
    {
        return '可以代替人工作';
    }
}

class Student
{
 public function study($who='人')
 {
     $man = new Person();
     return $who.$man-> work();
 }

 public function drive($what='机器')
 {
     $auto = new Mechine();
     return $what.$auto->run();
 }
}

$student = new Student;
echo $student->study('男人');
echo '<br>';
echo $student->drive('机器人');
echo "<hr>";
//工厂类
class Factory
{
    public static function create($className)
    {
        switch (strtolower($className)) {
            case 'per':
                return new Person();
                break;
            case 'mec':
                return new Mechine();
                break;
        }
    }
}

class Student1
{
    public function study($who='人')
    {
        $computer = Factory::create('per');
        return $who.$computer-> work();
    }

    public function drive($what='机器')
    {
        $auto = Factory::create('mec');;
        return $what.$auto->run();
    }
}

$student = new Student1;
echo $student->study('女人');
echo '<br>';
echo $student->drive('机器猫');


看完视频,做完案例,从案例并没有看出工厂模式带来什么具体好处

或者说不用工厂模式带来的坏处没看到太清楚

希望老师解答我的疑惑


发布手记

热门词条