Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7b17f7b

Browse files
cdocoZiHang Gao
authored and
ZiHang Gao
committed
Added: 添加抽象工厂
1 parent e143678 commit 7b17f7b

File tree

2 files changed

+99
-1
lines changed

2 files changed

+99
-1
lines changed

‎README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
#### 1. 创建型模型
77

88
- 简单工厂 [simple_factory](https://github.com/cdoco/php-patterns/blob/master/simple_factory.php)
9-
- 抽象工厂
9+
- 抽象工厂[abstract_factory](https://github.com/cdoco/php-patterns/blob/master/abstract_factory.php)
1010
- 建造者
1111
- 工厂方法
1212
- 原型

‎abstract_factory.php

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
<?php
2+
3+
/**
4+
* 抽象工厂模式
5+
*/
6+
abstract class Vehicle {
7+
8+
/**
9+
* 属性
10+
*
11+
* @var array
12+
*/
13+
private $props = array();
14+
15+
/**
16+
* 设置属性
17+
*
18+
* @param $key
19+
* @param $value
20+
*/
21+
public function setProperty($key, $value) {
22+
$this->props[$key] = $value;
23+
}
24+
25+
public function getProperty($key) {
26+
return $this->props[$key];
27+
}
28+
29+
}
30+
31+
abstract class Bus extends Vehicle {
32+
33+
/**
34+
* 车体形状
35+
*
36+
* @var
37+
*/
38+
public $shape;
39+
40+
/**
41+
* 设置形状
42+
*
43+
* @param $value
44+
*/
45+
public function setShape($value) {
46+
$this->shape = $value;
47+
}
48+
49+
abstract function run();
50+
}
51+
52+
53+
abstract class Car extends Vehicle {
54+
55+
/**
56+
* 两厢/三厢
57+
*
58+
* @var
59+
*/
60+
public $room;
61+
62+
public function setRoom($value) {
63+
$this->room = $value;
64+
}
65+
66+
public function getRoom() {
67+
return $this->room;
68+
}
69+
70+
abstract function run();
71+
}
72+
73+
//抽象工厂
74+
abstract class Factory {
75+
abstract static function create($className);
76+
}
77+
78+
class CarFactory extends Factory {
79+
80+
public static function create($className) {
81+
$class = $className;
82+
return new $class();
83+
}
84+
}
85+
86+
class Audi extends Car {
87+
88+
public function run() {
89+
90+
parent::setProperty('brand', 'audi');
91+
$brand = parent::getProperty('brand');
92+
$this->setRoom('threeRoom');
93+
return $this->room . '' . $brand . ' Car is running';
94+
}
95+
}
96+
97+
$Car = CarFactory::create('Audi');
98+
echo $Car->run();

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /