日期:2012-02-27  浏览次数:20407 次

复制代码 代码如下:

<?php
/*
边学边做的,为方便自己翻阅而发布,更为得到高人指点而发布,欢迎高手指点......
【提示】本例通过测试无误
【情景设计】
模拟计算机主板IDE接口,比如:主板可以存取的储存器常常有光驱、硬盘、闪存等等,
为了方便,有必要对这些不同的储存器设定同一的接口。
本例还假设一种前所未有的、存取方式与众不同的外星储存器也要加到主板上进行存取,
于是需要采用耦合的设计模式。
【本例主要讲述】
1、通过接口、抽象类、一般类继承三种方式达到所谓的“接口”模式,以此说明:
A、子类对象可以当父类对象用,因为子类是特殊的父类!
B、请注意这三种实现方式中接口、抽象类和一般类继承的基类写法!
2、接口模式真的是一纸契约!
3、程序设计之"耦合设计模式"!
*/
//----------------------------------------------------------------------
/*【方式一】接口实现方式:*/
interface readandwrite{
function read();
function write();
}
class motherboard{
private $storage;
function __construct(readandwrite $obj){
$this->storage=$obj;
}
function read(){
$this->storage->read();
}
function write(){
$this->storage->write();
}
}
class flash implements readandwrite{
function __construct(){
echo "我是闪存:<br>";
}
function read(){
echo "开始读取数据......<br>";
}
function write(){
echo "开始储存数据......<hr>";
}
}
class yingpan implements readandwrite{
function __construct(){
echo "我是硬盘:<br>";
}
function read(){
echo "开始读取数据......<br>";
}
function write(){
echo "开始储存数据......<hr>";
}
}
class disco implements readandwrite{
function __construct(){
echo "我是光盘:<br>";
}
function read(){
echo "开始读取数据......<br>";
}
function write(){
echo "开始储存数据......<hr>";
}
}
//----------------------------------------------------------------------
/*【方式二】抽象类实现方式:
abstract class readandwrite{
abstract function read();
abstract function write();
}
class motherboard{
private $storage;
function __construct(readandwrite $obj){
$this->storage=$obj;
}
function read(){
$this->storage->read();
}
function write(){
$this->storage->write();
}
}
class flash extends readandwrite{
function __construct(){
echo "我是闪存:<br>";
}
function read(){
echo "开始读取数据......<br>";
}
function write(){
echo "开始储存数据......<hr>";
}
}
class yingpan extends readandwrite{
function __construct(){
echo "我是硬盘:<br>";
}
function read(){
echo "开始读取数据......<br>";
}
function write(){
echo "开始储存数据......<hr>";
}
}
class disco extends readandwrite{
function __construct(){
echo "我是光盘:<br>";
}
function read(){
echo "开始读取数据......<br>";
}
function write(){
echo "开始储存数据......<hr>";
}
}
*/
//----------------------------------------------------------------------
//【方式三】一般类继承实现方式:
/*
class readandwrite{
function read(){
echo "reading..............";
}
function write(){
echo "writing..............";
}
}
class motherboard{
private $storage;
function __construct(readandwrite $obj){
$this->storage=$obj;
}
function read(){
$this->storage->read();
}
function write(){
$this->storage->write();
}
}
class flash extends readandwrite{
function __construct(){
echo "我是闪存:<br>";
}
function read(){
echo "开始读取数据......<br>";
}
function write(){
echo "开始储存数据......<hr>";
}
}
class yingpan extends readandwrite{
function __construct(){
echo "我是硬盘:<br>";
}
function read(){
echo "开始读取数据......<br>";
}
function write(){
echo "开始储存数据......<hr>";
}
}
class disco