The purpose of design patterns is: reuse.
In object-oriented, a class is a code template used to generate objects, and a design pattern is a code template used to solve common problems.
Following such a template, we can design excellent code quickly.
Note that design patterns are just templates, not specific codes.
It is for code reuse and increase maintainability .
When learning design patterns, there are several concepts that make me hard to accept. This may be the confinement from procedural programming to object-oriented programming.
Suppose there is such an object:
class Person
{
private $name = 'Human';
public function getName()
{
return $this->name;
}
}
1 Variable storage object
Don't think that variables can only store integer numbers, arrays and strings. Variables can also store objects:
$man = new Person;
echo $man->getName();
2 Passing object parameters
If another class uses the properties or methods of the Person class, just go directly into it:
class Student
{
public function __construct($person)
{
echo $person->getName();
}
}
// 传递对象,最后输出字符串“Human”
$jack = new Student(new Person);
But this has a small problem, when it new Student()
is not passed to an Person
object, as follows,
$jack = new Student('abc');
The program will report an error. So there is a third way to limit the type of parameters.
3 Limit the type of passed parameters
When passing parameters, limit the type of the parameter, write like this:
class Student
{
public function __construct(Person $person)
{
echo $person->getName();
}
}
// 传递对象,
$jack = new Student(new Person);
In this way, the passed new Student()
parameter must be Person
an instance.
4 Save objects with class attributes
There is also a frequently used method, which is to save an object or a collection of objects with a class attribute. as follows:
class Life
{
public $persons = [];
public function addPerson(Person $person)
{
$this->persons[] = $person;
}
}
$class = new Life();
$class->addPerson(new Person);
$class->addPerson(new Person);
var_dump($class->persons);
output value:
array(2) {
[0]=>
object(Person)#2 (1) {
["name":"Person":private]=>
string(5) "Human"
}
[1]=>
object(Person)#3 (1) {
["name":"Person":private]=>
string(5) "Human"
}
}
5 Summary
Object-oriented design patterns are formed after some combination of the above situation.
Therefore, understanding the relationship between classes is the key.
Cross- linked network + era, a time to keep learning, carrying hand one thousand Feng PHP , Dream It Possible .