小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

php設(shè)計模式之策略模式

 哇嘿嘿 2014-09-25
在此模式中,算法是從復(fù)雜類提取的,因而可以方便地替換。 例如,如果要更改搜索引擎中排列頁的方法,則策略模式是一個不錯的選擇。思考一下搜索引擎的幾個部分 —— 一部分遍歷頁面,一部分對每頁排列,另一部分基于排列的結(jié)果排序。在復(fù)雜的示例中,這些部分都在同一個類中。通過使用策略模式,您可將排列部分放入另一個 類中,以便更改頁排列的方式,而不影響搜索引擎的其余代碼。
 
 

 作為一個較簡單的示例,下面 顯示了一個用戶列表類,它提供了一個根據(jù)一組即插即用的策略查找一組用戶的方法

復(fù)制代碼
//定義接口
interface IStrategy {
    function filter($record);
}

//實現(xiàn)接口方式1
class FindAfterStrategy implements IStrategy {
    private $_name;
    public function __construct($name) {
        $this->_name = $name;
    }
    public function filter($record) {
        return strcmp ( $this->_name, $record ) <= 0;
    }
}

//實現(xiàn)接口方式1
class RandomStrategy implements IStrategy {
    public function filter($record) {
        return rand ( 0, 1 ) >= 0.5;
    }
}

//主類
class UserList {
    private $_list = array ();
    public function __construct($names) {
        if ($names != null) {
            foreach ( $names as $name ) {
                $this->_list [] = $name;
            }
        }
    }
    
    public function add($name) {
        $this->_list [] = $name;
    }
    
    public function find($filter) {
        $recs = array ();
        foreach ( $this->_list as $user ) {
            if ($filter->filter ( $user ))
                $recs [] = $user;
        }
        return $recs;
    }
}

$ul = new UserList ( array (
        "Andy",
        "Jack",
        "Lori",
        "Megan" 
) );
$f1 = $ul->find ( new FindAfterStrategy ( "J" ) );
print_r ( $f1 );

$f2 = $ul->find ( new RandomStrategy () );
復(fù)制代碼
print_r ( $f2 );  
策略模式非常適合復(fù)雜數(shù)據(jù)管理系統(tǒng)或數(shù)據(jù)處理系統(tǒng),二者在數(shù)據(jù)篩選、搜索或處理的方式方面需要較高的靈活性

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多