码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式-接口多态

时间:2015-02-26 18:07:49      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

<?php
//飞行接口
interface Flyable {
function fly($obj);
}
//飞行接口类的具体实现
class Action implements Flyable{
function fly($obj){
if($obj instanceof Aduck){
echo ‘Aduck is flying<br/>‘;
}else if($obj instanceof Bduck){
echo ‘Bduck is flying<br/>‘;
}else{
echo ‘cannot fly<br/>‘;
}
}
}

//基类
class Duck {
protected $_flyAction;
public function __construct(){
$this->_flyAction = new Action();
}
public function shape(){
echo ‘duck shape‘;
}

public function life() {
echo ‘a duck life‘;
}
}


//A子类
class Aduck extends Duck {
public function fly(){
echo $this->_flyAction->fly($this);
}
}

//B子类
class Bduck extends Duck {
public function fly(){
echo $this->_flyAction->fly($this);
}
}

//C子类
class Cduck extends Duck {
public function fly(){
echo $this->_flyAction->fly($this);
}
}

$a = new Aduck();
$b = new Bduck();
$c = new Cduck();

$a->fly();
$b->fly();
$c->fly();

 

设计模式-接口多态

标签:

原文地址:http://www.cnblogs.com/b13272012771/p/4301556.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!