diff --git a/includes/framework/class-factory.php b/includes/framework/class-factory.php index 02c66b5e..6d5588f6 100644 --- a/includes/framework/class-factory.php +++ b/includes/framework/class-factory.php @@ -15,11 +15,11 @@ abstract class Factory { /** - * Container for the main instance of the class. + * Container for the main instance of each factory subclass, keyed by class name. * - * @property ?Model + * @var array, static> */ - protected static $instance = null; + protected static $instances = array(); /** * Instantiates a model object. @@ -33,15 +33,16 @@ abstract public function make( $args ); /** * Utility method to retrieve the main instance of the class. * - * The instance will be created if it does not exist yet. + * The instance will be created if it does not exist yet. Each subclass + * has its own instance. * - * @return Model The main instance. + * @return static The main instance. */ public static function get_instance() { - if ( null === self::$instance ) { - self::$instance = new static(); + if ( ! isset( self::$instances[ static::class ] ) ) { + self::$instances[ static::class ] = new static(); } - return self::$instance; + return self::$instances[ static::class ]; } } diff --git a/tests/phpunit/tests/framework/test-factory.php b/tests/phpunit/tests/framework/test-factory.php new file mode 100644 index 00000000..b4e7b651 --- /dev/null +++ b/tests/phpunit/tests/framework/test-factory.php @@ -0,0 +1,42 @@ +assertInstanceOf( Factory\Message::class, Factory\Message::get_instance() ); + $this->assertInstanceOf( Factory\Notification::class, Factory\Notification::get_instance() ); + $this->assertInstanceOf( Factory\Subscription::class, Factory\Subscription::get_instance() ); + } + + /** + * Should not share one instance across factory subclasses. + */ + public function test_get_instance_is_distinct_per_subclass() { + $message = Factory\Message::get_instance(); + $notification = Factory\Notification::get_instance(); + $subscription = Factory\Subscription::get_instance(); + + $this->assertNotSame( $message, $notification ); + $this->assertNotSame( $message, $subscription ); + $this->assertNotSame( $notification, $subscription ); + } + + /** + * Should return the same instance on repeated calls for the same subclass. + */ + public function test_get_instance_is_singleton_per_subclass() { + $this->assertSame( Factory\Message::get_instance(), Factory\Message::get_instance() ); + $this->assertSame( Factory\Notification::get_instance(), Factory\Notification::get_instance() ); + $this->assertSame( Factory\Subscription::get_instance(), Factory\Subscription::get_instance() ); + } +}