php,如何防止直接类实例化?

Joh*_*ith 0 php

假设我有一个非常普通的课程:

class Money
{
    public __construct($actualCountry)
    {
        $this->actualCountry = $actualCountry;
    }

    public function getValute()
    {
        return according to actual country
    }
}
Run Code Online (Sandbox Code Playgroud)

这个类需要创建一次,所以我有一个全局工厂:

final class Factory
{
    private $money;

    public function getMoney()
    {
        if ($this->money == null)
        {
            $this->money = new Money(Config::getCountryCode());
        }
        return $this->money;
    }
}
Run Code Online (Sandbox Code Playgroud)

每当我们想要使用:

Factory::getMoney()->
Run Code Online (Sandbox Code Playgroud)

但今天我看到我的同事试图这样做:

(new Money(Config::getCountryCode()))->getValute();
Run Code Online (Sandbox Code Playgroud)

这显然是错误的,不需要多次出现。但是类本身怎么能说“嘿,不要实例化我,使用工厂”呢?

我无法将其设置为单例,因为每次都会:

Money::getInstance(Config::getCountryCode());
Run Code Online (Sandbox Code Playgroud)

毫无意义。

但真正的问题不是因为它可能存在多个 - 这是我总是必须从配置中传递当前国家/地区的方式。什么是Config变得GlobalConfig?这就是为什么工厂要避免大量参数传递(如果有更多参数怎么办Money?)

小智 5

我认为你应该再次考虑单例模式。它更适合您想要的逻辑。

<?php
class Money
{
    private static $instance;

    private function __construct($countryCode)
    {
        #your code here...
    }

    /**
     * Do not include parameter for getInstance.
     * Make the call internally.
     * Now when you have to change Config to GlobalConfig will be painless.
     */
    public static function getInstance()
    {
        if (null === self::$instance) {
            return self::$instance = new Money(Config::getCountryCode());
        }

        return  self::$instance;
    }
}
Run Code Online (Sandbox Code Playgroud)