单例模式与抽象工厂模式结合实例

abstract class ApptEncoder{
    abstract function encode();
}

class BloggsApptEncoder extends ApptEncoder{
    function encode(){
        return 'this is bloggs object';
    }
}

class MegaApptEncoder extends ApptEncoder{
    function encode(){
        return 'this is mega object';
    }
}

abstract class CommsManager{
    abstract function getHeaderText();
    abstract function getApptEncoder();
    abstract function getFooterText();
}

class BloggsCommsManager extends CommsManager{
    function getHeaderText(){
        return 'this is bloggs header';
    }

    function getApptEncoder(){
        return new BloggsApptEncoder();
    }

    function getFooterText(){
        return 'this is bloggs footer';
    }
}

class MegeCommsManger extends CommsManager{
    function getHeaderText(){
        return 'this is mega header';
    }

    function getApptEncoder(){
        return new MegaApptEncoder();
    }

    function getFooterText(){
        return 'this is mega footer';
    }
}

class Settings{
    static $COMMSTYPE = 'Bloggs';
}

class AppConfig{
    private static $instance;
    private $commsManager;

    //将构造方法设置为私有,可以防止继承
    private function __construct(){
        //只会运行一次
        $this->init();
    }

    private function init(){
        switch (Settings::$COMMSTYPE){
            case 'Mega':
                $this->commsManager = new MegaCommsManager();
                break;
            default:
                $this->commsManager = new BloggsCommsManager();
        }
    }

    public static function getInstance(){
        if(empty(self::$instance)){
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function getCommsManager(){
        return $this->commsManager;
    }
}

$commsMgr = AppConfig::getInstance()->getCommsManager();
$commsMgr->getApptEncoder()->encode();






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值