首页 > 其他 > 详细

工厂模式的简单原理

时间:2019-12-24 01:30:11      阅读:125      评论:0      收藏:0      [点我收藏+]

工厂模式:顾名思义就是创建对象或者特定资源的设计容器;

技术分享图片
<?php

    /**工厂模式:解决类与类之间的高耦合问题,实现类内部的高聚合,低耦合
     *设计思想:当类的资源会在项目中高频的调用,若该类的生成方法有变化(如创建对象添加了参数),则必须在依赖此类的所有文件中动态的做出修改,
     * 十分繁琐不方便且容易出错,工厂模式正是解决类之间的高度耦合问题,使得类的构造交给某个特定的工厂类,需要调用此类资源的其他文件只需依赖于
     * 某个特定的工厂类,降低耦合度;
     *
     * 工厂模式的粗糙展示
     * */
    //能力接口
    interface power
    {
        function fly();

        function shoot();
    }

    //兽族工厂
    class Orcs implements power
    {
        function fly()
        {
            return ‘the animal has a pair of wings‘;
        }

        function shoot()
        {
            return ‘the animal can use guns‘;
        }
    }

    //人族
    class Man implements power
    {
        function fly()
        {
            return ‘the man can fly with airplane‘;
        }

        function shoot()
        {
            return ‘the man is the inventor of hot weapon‘;
        }
    }
    class Factory
    {
        public static function createHero($type)
        {
            switch($type){
                case ‘man‘:
                    return new Man;
                    break;
                case ‘orcs‘:
                    return new Orcs;
                    break;
            }
        }
    }

    //类通过工厂类构造,当类的创建方式有所变化时,只需修改工厂类中的构造形式即可
    $man = Factory::createHero(‘man‘);
    echo $man->fly()."<br />";

    $orcs = Factory::createHero(‘orcs‘);
    echo $orcs->shoot();
工厂模式

工厂模式的简单原理

原文:https://www.cnblogs.com/jianbing123/p/12089168.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!