1. 程式人生 > 實用技巧 >php 設計模式之抽象工廠模式

php 設計模式之抽象工廠模式



1. 抽象工廠模式

還是將實現推遲到子類,但是抽象工廠裡面不僅僅只返回一個物件,而是返回一堆


2. 實列

interface Message {
    public function send(string $msg);
}

class AliMessage implements Message {
    public function send(string $msg) {
        return '阿里雲簡訊內容:' . $msg;
    }
}

class BaiduMessage implements Message {
    public function send(string $msg) {
        return '百度SMS簡訊內容:' . $msg;
    }
}


interface Push {
    public function send(string $msg);
}

class AliPush implements Push {
    public function send(string $msg) {
        return '阿里雲傳送成功:' . $msg;
    }
}

class BaiduPush implements Push {
    public function send(string $msg) {
        return '百度傳送成功:' . $msg;
    }
}


interface MessageFactory{
    public function createMessage();
    public function createPush();
}

class AliFactory implements MessageFactory {
    public function createMessage() {
        return new AliMessage();
    }
    public function createPush() {
        return new AliPush();
    }
}

class BaiduFactory implements MessageFactory {
    public function createMessage() {
        return new BaiduMessage();
    }
    public function createPush() {
        return new BaiduPush();
    }
}

$factory = new AliFactory();
// $factory = new BaiduFactory();
$message = $factory->createMessage();
$push = $factory->createPush();
echo $message->send('您已經很久沒有登入過系統了,記得回來哦!');
echo $push->send('您有新的紅包已到帳,請查收!');