Skip to content

Commit 1be5f13

Browse files
committed
Factory Method
1 parent 55caa45 commit 1be5f13

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

Factorymethod/index.php

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
<?php
2+
3+
/**
4+
* Design pattern "Factory method" / "Virtual Constructor" (Creational)
5+
* This is demo code
6+
* See for details: http://maxsite.org/page/php-patterns
7+
*/
8+
9+
/**
10+
* Base class
11+
*/
12+
abstract class CommonAbstract
13+
{
14+
/**
15+
* Create new class
16+
*/
17+
public static function initial($class)
18+
{
19+
return new $class();
20+
}
21+
22+
/**
23+
* Common methods
24+
*/
25+
abstract public function run();
26+
}
27+
28+
/**
29+
* Class1 for sample
30+
*/
31+
class Class1 extends CommonAbstract
32+
{
33+
public function run()
34+
{
35+
echo 'Class1 run<br>';
36+
}
37+
}
38+
39+
/**
40+
* Class2 for sample
41+
*/
42+
class Class2 extends CommonAbstract
43+
{
44+
public function run()
45+
{
46+
echo 'Class2 run<br>';
47+
}
48+
}
49+
50+
51+
/**
52+
* demo
53+
*/
54+
55+
$a = CommonAbstract::initial('Class1');
56+
$a->run();
57+
/*
58+
Class1 run
59+
*/
60+
61+
$b = CommonAbstract::initial('Class2');
62+
$b->run();
63+
/*
64+
Class2 run
65+
*/
66+
67+
# end of file

0 commit comments

Comments
 (0)