php接口、工厂函数

//图像接口
interface img{
    public function getWidth();
    public function getHeight();
    public function getData();
}

//png图像处理
class Img_PNG implements img{
    private $width, $height, $data;

    public function __construct($file){
        $this->file = $file;
        $this->parse();
    }
    public function parse(){
        echo '这里对png格式图形进行处理<br>';
    }
    public function getWidth(){
        return $this->width;
    }
    public function getHeight(){
        return $this->height;
    }
    public function getData(){
        return $this->data;
    }
}
//jpeg图像处理
class Img_JPEG implements img{
    private $width, $height, $data;

    public function __construct($file){
        $this->file = $file;
        $this->parse();
    }
    public function parse(){
        echo '这里对JPEG格式图形进行处理<br>';
    }
    public function getWidth(){
        return $this->width;
    }
    public function getHeight(){
        return $this->height;
    }
    public function getData(){
        return $this->data;
    }
}
//图像工厂
class ImgFactory{
    public static function factory($file) {
        $pathParts = pathinfo($file);
        $ext = strtolower($pathParts['extension']);
        switch($ext) {
            case 'png':
                $ret = new Img_PNG($file);
                break;
            case 'jpeg':
            case 'jpg':
                $ret = new Img_JPEG($file);
                break;
            default:
                return false;
        }

        if ($ret instanceof Img) {
            return $ret;
        } else {
            return false;
        }
    }
}


$img1 = ImgFactory::factory('ab/cc/aa.png');
$img2 = ImgFactory::factory('ab/cc/aa.jpeg');
$img3 = ImgFactory::factory('ab/cc/aa.jpg');
$img3 = ImgFactory::factory('ab/cc/aa.aaa');

 

posted on 2013-07-07 11:20  zper  阅读(338)  评论(0编辑  收藏  举报

导航