header(
"Content-type:text/html; charset=utf-8"
);
abstract
class
Component {
abstract
function
addNode(Component
$obj
);
abstract
function
removeNode(Component
$obj
);
abstract
function
show(
$str
);
}
class
Branch
extends
Component {
public
$name
='';
public
$childNode
=
array
();
public
function
__construct(
$name
)
{
$this
->name =
$name
;
}
public
function
addNode(Component
$obj
) {
array_push
(
$this
->childNode,
$obj
);
}
public
function
removeNode(Component
$obj
) {
$key
=
array_search
(
$obj
,
$this
->childNode);
unset(
$this
->childNode[
$key
]);
}
public
function
show(
$str
=
""
) {
echo
$this
->name.
"<br>"
;
$str
.=
" |- "
;
foreach
(
$this
->childNode
as
$val
) {
echo
$str
;
$val
->show(
$str
);
}
}
}
class
Leaf
extends
Component {
public
$name
;
public
function
__construct(
$name
) {
$this
->name =
$name
;
}
function
addNode(Component
$obj
) {
return
false;
}
function
removeNode(Component
$obj
) {
return
false;
}
function
show(
$str
=
""
) {
echo
$this
->name.
"<br>"
;
}
}
$branch1
=
new
Branch(
"家电类"
);
$leaf11
=
new
Leaf(
"电饭煲"
);
$leaf12
=
new
Leaf(
"电冰箱"
);
$leaf13
=
new
Leaf(
"洗衣机"
);
$branch1
->addNode(
$leaf11
);
$branch1
->addNode(
$leaf12
);
$branch1
->addNode(
$leaf13
);
$branch2
=
new
Branch(
"电脑类"
);
$branch21
=
new
Branch(
"台式机"
);
$branch22
=
new
Branch(
"笔记本"
);
$leaf221
=
new
Leaf(
"华硕"
);
$leaf222
=
new
Leaf(
"联想"
);
$leaf223
=
new
Leaf(
"华为"
);
$leaf224
=
new
Leaf(
"华夏"
);
$branch22
->addNode(
$leaf221
);
$branch22
->addNode(
$leaf222
);
$branch22
->addNode(
$leaf223
);
$branch22
->addNode(
$leaf224
);
$branch2
->addNode(
$branch21
);
$branch2
->addNode(
$branch22
);
$branch1
->addNode(
$branch2
);
$branch1
->show();