Singleton mode
private static variables (to store instances), private constructor methods (to prevent creation of instances), private clone methods (to prevent cloning of objects), public static methods (to provide instances to the outside world)
Application Scenarios:
When database operations are involved in a program application, connecting to the database during each operation will cause a lot of resource consumption. You can create a unique database connection object by using the single instance pattern.
1
2
3
4
5
6
7
8
9
10
11
|
<?phpclass Singleton{
private static $_instance ;
private function __construct(){}
private function __clone(){}
public static function getInstance()
{
if (self:: $_instance instanceof Singleton){//instanceof Determine if an instance is an object of a class
self:: $_instance = new Singleton();
}
return self:: $_instance ;
}}
|
Factory Model
Separate the calling object from the creating object, the caller requests directly to the factory, reducing the coupling of code. Improve the maintainability and scalability of the system.
Application Scenarios:
Provide a class that has certain methods for creating objects for you, so that you can create objects using the factory class instead of using new directly, so that if you want to change the type of object created, you can just change the factory.
1
2
3
4
5
6
7
8
9
10
|
//Assume 3 classes to be instantiated
class Aclass{}class Bclass{}class Cclass{}class Factory{
//Define the class name of each class
const ACLASS = 'Aclass' ;
const BCLASS = 'Bclass' ;
const CCLASS = 'Cclass' ;
public static function getInstance( $newclass )
{
$class = $newclass ;//This is often used in real projects to parse routes and load files.
return new $class ;
}} //调用方法:Factory::getInstance(Factory::ACLASS);
|
Registration Tree Model
The Registered Tree pattern is a pattern design approach by registering object instances to a global object tree and picking from the object tree when needed.
It doesn't matter if the object is generated by the singleton pattern or the factory pattern or a combination of the two, just "plug it in" to the registration tree. When I use an object, I just fetch it from the tree. This is as convenient and useful as using global variables. And the registration tree pattern also provides a very good idea for other patterns. (The following example is a joint use of singleton, factory, and registry tree)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
//Creating a single instance
class Single{
public $hash ;
static protected $ins =null;
final protected function __construct(){
$this ->hash=rand(1,9999);
}
static public function getInstance(){
if (self:: $ins instanceof self) {
return self:: $ins ;
}
self:: $ins = new self();
return self:: $ins ;
}}//Factory Model
class RandFactory{
public static function factory(){
return Single::getInstance();
}} //注册树class Register{
protected static $objects ;
public static function set( $alias , $object ){
self:: $objects [ $alias ]= $object ;
}
public static function get( $alias ){
return self:: $objects [ $alias ];
}
public static function _unset( $alias ){
unset(self:: $objects [ $alias ]);
}} //调用Register::set('rand',RandFactory::factory());$object=Register::get('rand');print_r($object);
|
Strategy Mode
Define a series of algorithms, encapsulate each one, and make them interchangeable. The policy pattern allows an algorithm to change independently of the client using it.
The policy pattern provides a way to manage related families of algorithms; the policy pattern provides a way to replace inheritance relationships; and using the policy pattern avoids the use of multiple conditional transfer statements.
Application Scenarios:
Multiple classes differ only in the behavior they exhibit, and you can use the Strategy pattern to dynamically choose the specific behavior to perform at runtime. For example, to go to school, there are multiple strategies: walking, bus, subway...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
abstract class Strategy{
abstract function goSchool();} class Run extends Strategy{
public function goSchool()
{
// TODO: Implement goSchool() method.
}} class Subway extends Strategy{
public function goSchool()
{
// TODO: Implement goSchool() method.
}} class Bike extends Strategy{
public function goSchool()
{
// TODO: Implement goSchool() method.
}} class Context{
protected $_stratege ;//Store the passed policy object
public function goSchoole()
{
$this ->_stratege->goSchoole();
}} //调用:$contenx = new Context();$avil_stratery = new Subway();$contenx->goSchoole($avil_stratery);
|
Adapter Mode
The API is a unified API that encapsulates a variety of very different functional interfaces.
A similar scenario is the cache adapter, which can unify different cache functions such as memcache, redis, file, apc, etc. into a consistent API。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
abstract class Toy{
public abstract function openMouth();
public abstract function closeMouth();} class Dog extends Toy{
public function openMouth()
{
echo "Dog open Mouth\n" ;
}
public function closeMouth()
{
echo "Dog close Mouth\n" ;
}} class Cat extends Toy{
public function openMouth()
{
echo "Cat open Mouth\n" ;
}
public function closeMouth()
{
echo "Cat close Mouth\n" ;
}}
interface RedTarget{
public function doMouthOpen();
public function doMouthClose();}
interface GreenTarget{
public function operateMouth( $type = 0);}
class RedAdapter implements RedTarget{
private $adaptee ;
function __construct(Toy $adaptee )
{
$this ->adaptee = $adaptee ;
}
public function doMouthOpen()
{
$this ->adaptee->openMouth();
}
public function doMouthClose()
{
$this ->adaptee->closeMouth();
}}
class GreenAdapter implements GreenTarget{
private $adaptee ;
function __construct(Toy $adaptee )
{
$this ->adaptee = $adaptee ;
}
Adaptee:GreenTarget的operateMouth方法
public function operateMouth( $type = 0)
{
if ( $type ) {
$this ->adaptee->openMouth();
} else {
$this ->adaptee->closeMouth();
}
}} class testDriver{
public function run()
{
//Instantiate a dog toy
$adaptee_dog = new Dog();
echo "Putting a date adapter on a dog\n";
$adapter_red = new RedAdapter( $adaptee_dog );
//Open your mouth
$adapter_red ->doMouthOpen();
//Shut up!
$adapter_red ->doMouthClose();
echo "Putting an adapter on the dog\n";
$adapter_green = new GreenAdapter( $adaptee_dog );
//Open your mouth
$adapter_green ->operateMouth(1);
//闭嘴
$adapter_green ->operateMouth(0);
}} //调用$test = new testDriver();$test->run();
|
Observer pattern
Observer pattern (Observer), when the state of an object changes, all the objects that depend on it will receive a notification and automatically update. The Observer pattern implements a low-coupling, non-intrusive notification and update mechanism.
After an event occurs, a sequence of update operations is performed. The traditional way of programming is to add processing logic directly after the code of the event. When the logic for updates increases, the code becomes difficult to maintain. This approach is coupled and intrusive, and adding new logic requires modifying the event's body code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
interface Subject{
public function register(Observer $observer );
public function notify();}
interface Observer{
public function watch();}
class Action implements Subject{
public $_observers =[];
public function register(Observer $observer ){
$this ->_observers[]= $observer ;
}
public function notify(){
foreach ( $this ->_observers as $observer ) {
$observer ->watch();
}
}}
class Cat1 implements Observer{
public function watch(){
echo "Cat1 watches TV<hr/>" ;
}}
class Dog1 implements Observer{
public function watch(){
echo "Dog1 watches TV<hr/>" ;
}
}
class People implements Observer{
public function watch(){
echo "People watches TV<hr/>" ;
}
}
$action=new Action();$action->register(new Cat1());$action->register(new People());$action->register(new Dog1());$action->notify();
|