jpc/design-pattern

1.1.0 2020-11-12 09:46 UTC

This package is auto-updated.

Last update: 2024-09-12 18:21:32 UTC


README

DesignPattern 库允许你简单地将设计模式如 SingletonMultiton 包含到你的类中。

安装

使用 composer require jpc/design-pattern 通过 composer 安装。

如何使用

创建单例类

创建你想要成为单例类的类。

<?php
	class MySingletonClass {
    	// Some properties and functions
        
        public function __construct($myFristParam, $mySecondParam){
        	//...
        }
    }
?>

然后,添加 Singleton 特性。

<?php
	class MySingletonClass {
    
    	use JPC\DesignPattern\Singleton;
    
    	// Some properties and functions
        
        public function __construct($myFristParam, $mySecondParam){
        	//...
        }
    }
?>

获取单例类

你可以简单地使用静态函数 getInstance 来获取单例实例。

//Some Code
$mySingleton = MySingletonClass::getInstance($param1, $param2);
//Some Code

对于 Multiton

单例和多例的唯一区别在于获取实例时,你必须传递一个标识符,如下所示

//Some Code
$myMultiton = MyMultitonClass::getInstance("IDENTIFIER", $param1, $param2);
//Some Code

这允许你使用不同的参数创建不同的实例。

感谢您!

感谢您阅读,也许还会下载和使用这个库!如果您有任何请求,请告诉我,我会为您编写代码!