php设计模式-策略模式

策略模式的实现通常通过声明一个抽象的拥有一个算法方法的基类来实现,而且通过继承这个基类的具体类来实现,在代码的一些关键点,设计模式将决定哪个具体的策略是相关的,然后实例化,并使用相关的类。

比如,我们实现一个这样的需求,网站提供下载文件,这个页面会根据web客户端的操作系统生成对应的文件类型,如果linux系统,生成.tar.gz类型的文件,如果是Windows,生成.zip类型的文件。

 1 abstract class FileNamingStrategy{
 2     abstract function createLinkName( $fileName );
 3 }
 4 
 5 class ZipFileNamingStrategy extends FileNamingStrategy{
 6     function createLinkName( $fileName ){
 7         return $fileName . ".zip";
 8     }
 9 }
10 
11 class TarFileNamingStrategy extends FileNamingStrategy{
12     function createLinkName( $fileName ){
13         return $fileName . ".tar.gz";
14     }
15 }
16 
17 if( strstr( $_SERVER['HTTP_USER_AGENT'], 'Win' ) ) {
18     $obj = new ZipFileNamingStrategy();
19 }else {
20     $obj = new TarFileNamingStrategy();
21 }
22 
23 $file1 = $obj->createLinkName( "test1" );
24 $file2 = $obj->createLinkName( "test2" );
25 
26 print <<<EOF
27 <a href="$file1">test1</a>
28 <a href="$file2">test2</a>
29 EOF;

 

posted @ 2018-02-23 09:56  ghostwu  阅读(278)  评论(0编辑  收藏  举报
Copyright ©2017 ghostwu