当前位置:   article > 正文

六大原则与设计模式

六大原则与设计模式

1. 六大原则

1.1 单一原则(SRP)

应该有且仅有一个原因引起类的变更

1. 复杂性降低,可读性高,可维护性提高

2. 变更引起的风险降低,变更是必不可少的,如果接口的单一职责做得好,一个接口修改只对相应的实现类有影响,对其他的接口无影响,这对系统的扩展性、维护性都有非常大的帮助。

  1. class a{
  2. public function info(){
  3. echo "第一条消息";
  4. }
  5. }
  6. class b{
  7. public function text(){
  8. echo "第二条消息";
  9. }
  10. }
  11. class c {
  12. public function run(){
  13. $a = new a();
  14. $a->info();
  15. $b = new b();
  16. $b->text();
  17. }
  18. }
  19. $c = new c();
  20. $c->run();
1.2 开闭原则

类应该对扩展开放,对修改关闭

  1. interface A{
  2. public function boot();
  3. }
  4. class B implements A{
  5. public function boot(){
  6. return rand(1,100);
  7. }
  8. }
  9. class cli{
  10. public function run(){
  11. $b= new B();
  12. return $b->boot();
  13. }
  14. }
  15. $cli = new cli();
  16. echo $cli->run();
1.3 里氏替换原则

子类必须能够替换掉它们的基类

  1. class A{
  2. public function a(){
  3. return "电子产品";
  4. }
  5. }
  6. class B extends A{
  7. public function a()
  8. {
  9. return "手机";
  10. }
  11. }
  12. class client
  13. {
  14. public function run()
  15. {
  16. $b = new B();
  17. echo $b->a();
  18. }
  19. }
  20. $client = new client();
  21. $client->run();
1.4 依赖倒置原则

高层模块不应该依赖于低层模块,它们都应该依赖于抽象。

  1. interface A{
  2. public function str();
  3. }
  4. class B implements A{
  5. public function str()
  6. {
  7. return rand(1,100);
  8. }
  9. }
  10. class C implements A{
  11. public function str()
  12. {
  13. return "123";
  14. }
  15. }
1.5 接口隔离原则 (ISP)   

类不应该依赖于它不需要的接口

  1. interface A{
  2. public function a();
  3. public function b();
  4. }
  5. class B implements A{
  6. public function a()
  7. {
  8. return "a";
  9. }
  10. public function b()
  11. {
  12. return "b";
  13. }
  14. }

1.6 迪米特法则

优先使用对象组合而不是类继承

class a{
    protected  $user;
    public  function __construct(\think\App $app)
    {
        $this->user=$app;
    }

    public function index($id){
        return $this->user->index($id);
    }
}

这些原则有助于写出高内聚、低耦合的代码,使得代码更易于维护和扩展。

2. 设计模式

2.1 结构型模式
2.1.1 装饰器模式

装饰器模式用于动态地将新的行为添加到对象上,对于需要扩展功能的类来说是一种更加灵活的设计方案。在PHP中,可以使用装饰器模式来为已有的对象添加新的行为,不需要修改已有类的代码。

装饰器的优点:

1. 不改变代码的情况下对原代码的功能职责进行扩展,遵守了开闭原则

2. 每个类都有属于自己的功能职责

  1. interface MobileCase
  2. {
  3. public function boot();
  4. }
  5. class Mobile implements MobileCase
  6. {
  7. public function boot()
  8. {
  9. echo "无色无图案手机壳".PHP_EOL;
  10. }
  11. }
  12. abstract class MobileDecorator implements MobileCase
  13. {
  14. protected $mobileCase;
  15. public function __construct(MobileCase $mobileCase)
  16. {
  17. $this->mobileCase = $mobileCase;
  18. }
  19. public function boot()
  20. {
  21. $this->mobileCase->boot();
  22. }
  23. }
  24. class HedMobileCase extends MobileDecorator
  25. {
  26. private $name = "红色手机壳";
  27. private function add()
  28. {
  29. echo $this->name.PHP_EOL;
  30. }
  31. public function boot()
  32. {
  33. $this->mobileCase->boot();
  34. $this->add();
  35. }
  36. }
  37. class GreenMobileCase extends MobileDecorator
  38. {
  39. private $name = "黄色手机壳";
  40. private function add()
  41. {
  42. echo $this->name.PHP_EOL;
  43. }
  44. public function boot()
  45. {
  46. $this->mobileCase->boot();
  47. $this->add();
  48. }
  49. }
  50. class client
  51. {
  52. public function run()
  53. {
  54. $MobileCase = new Mobile();
  55. $HedMobileCase = new HedMobileCase($MobileCase);
  56. $HedMobileCase->boot();
  57. }
  58. }
  59. $client = new client();
  60. $client->run();
2.1.2 facade门面模式

又称为外观模式,为子系统中的一组接口提供一个统一的高层接口, 使得子系统更容易使用

门面模式的组成:

1. 外观角色 :模式的核心,被客户 Client 调用,知道各个子系统的概念。

2. 子系统角色 :实现子系统的功能。

3. 客户角色 :调用 Facade 角色获取相应的功能。

门面模式的优缺点:

1. 降低系统的复杂程度 2. 低耦合 3. 使用简单 4. 可能违背开闭原则

  1. class Connection
  2. {
  3. private function conn()
  4. {
  5. try {
  6. $connection = new PDO('mysql:host=127.0.0.1;dbname=starsky','root','root');
  7. return $connection;
  8. }catch (PDOException $exception){
  9. echo $exception->getMessage();
  10. }
  11. }
  12. public function run()
  13. {
  14. return $this->conn();
  15. }
  16. }
  17. class DBQuery
  18. {
  19. public function query(Connection $connection,$sql)
  20. {
  21. try {
  22. $pdo = $connection->run();
  23. $restful = $pdo->query($sql)->fetchAll();
  24. return $restful;
  25. }catch (PDOException $exception){
  26. echo $exception->getMessage();
  27. }
  28. }
  29. }
  30. class facade
  31. {
  32. private $query;
  33. private $conn;
  34. public function __construct()
  35. {
  36. $this->query = new DBQuery();
  37. $this->conn = new Connection();
  38. }
  39. public function select($sql)
  40. {
  41. return $this->query->query($this->conn,$sql);
  42. }
  43. }
  44. class DB
  45. {
  46. private static $query;
  47. public static function select($sql)
  48. {
  49. static::$query = new facade();
  50. return self::$query->select($sql);
  51. }
  52. }
  53. var_dump(DB::select('select * from `user`'));
2.1.3 注册树模式

通过将对象实例注册到一棵全局的对象树上,需要的时候从对 象树上采摘的模式设计方法

1. Laravel框架的服务容器          2. Thinkphp框架

  1. class Container
  2. {
  3. private $bindings = [];
  4. public function bind($abstract, $concrete = null, $shared = false)
  5. {
  6. $this->bindings[$abstract]['concrete'] = $concrete;
  7. $this->bindings[$abstract]['shared'] = $shared;
  8. }
  9. public function make($abstract,$parameters = [])
  10. {
  11. $object = $this->bindings[$abstract]['concrete'];
  12. if ($object instanceof \Closure){
  13. return $object();
  14. }
  15. if (!is_object($object)){
  16. $object = new $object(...$parameters);
  17. }
  18. return $object;
  19. }
  20. public function delete($abstract)
  21. {
  22. unset($this->bindings[$abstract]);
  23. }
  24. }
  25. class A
  26. {
  27. public function run()
  28. {
  29. echo "这里是A类的run方法";
  30. }
  31. }
  32. $container = new Container();
  33. $container->bind('a',new A());
  34. $container->make('a')->run();
  35. class Container
  36. {
  37. //用于存储实例化的对象或者类的命名空间
  38. private $bindings = [];
  39. //注册对象到$bindings数组里面,进行存储
  40. public function bind($abstract, $concrete = null)
  41. {
  42. $this->bindings[$abstract] = $concrete;
  43. }
  44. }
  45. class A{
  46. }
  47. $container = new Container();
  48. $container->bind('A',new A());
  49. interface I
  50. {
  51. public function boot();
  52. }
  53. /**
  54. * Class A php项目生成的数据 => 给java语言接口
  55. */
  56. class A implements I
  57. {
  58. public function boot()
  59. {
  60. $data = ["id" =>1,"name" => "starsky"];
  61. return json_encode($data);
  62. }
  63. }
  64. /**
  65. * Class B java生成的数据 =>php语言接口
  66. */
  67. class B implements I
  68. {
  69. public function boot()
  70. {
  71. $data = ["id" =>1,"name" => "starsky"];
  72. return serialize($data);
  73. }
  74. }
  75. interface I_Apadtor
  76. {
  77. public function boot(I $i);
  78. }
  79. class Apadtor implements I_Apadtor
  80. {
  81. public function boot(I $i)
  82. {
  83. if (!is_null($string = json_decode($i->boot()))){
  84. return serialize($string);
  85. }else{
  86. $string = unserialize($i->boot());
  87. return json_encode($string);
  88. }
  89. }
  90. }
  91. $Apadtor = new Apadtor();
  92. //java端调用php端数据
  93. var_dump("java调用php的数据:".$Apadtor->boot(new A()));
  94. //php端调用java端数据
  95. var_dump("php调用java的数据:".$Apadtor->boot(new B()));

2.1.4 适配器模式

将一个类的接口,转换成客户期望的另一个类的接口。适配器让原 本接口不兼容的类可以合作无间。

  1. interface I
  2. {
  3. public function boot();
  4. }
  5. class A implements I
  6. {
  7. public function boot()
  8. {
  9. $data = ["name" => "starsky","age" => 100,"sex" => 1];
  10. return serialize($data);
  11. }
  12. }
  13. class B implements I
  14. {
  15. public function boot()
  16. {
  17. $data = ["name" => "starsky","age" => 100,"sex" => 1];
  18. return json_encode($data);
  19. }
  20. }
  21. interface I_Adaptor
  22. {
  23. public function boot(I $i);
  24. }
  25. class Adaptor implements I_Adaptor
  26. {
  27. public function boot(I $in)
  28. {
  29. if (!is_null($string = json_decode($in->boot()))){
  30. return serialize($string);
  31. }else{
  32. $string = unserialize($in->boot());
  33. return json_encode($string);
  34. }
  35. }
  36. }
  37. $Adaptor = new Adaptor();
  38. var_dump(json_decode($Adaptor->boot((new A()))));
  39. var_dump(unserialize($Adaptor->boot((new B ()))));
2.1.5 Pipeline模式

应用场景: 1.订单生成 2.Laravel中中间件的执行

  1. class A
  2. {
  3. public static function handle($request)
  4. {
  5. echo "这里A类的Boot方法".PHP_EOL;
  6. }
  7. }
  8. class B
  9. {
  10. public static function handle($request)
  11. {
  12. echo "这里是B类的Boot方法".PHP_EOL;
  13. }
  14. }
  15. class C
  16. {
  17. public static function handle($request)
  18. {
  19. echo "这里是C类的Index方法".PHP_EOL;
  20. }
  21. }
  22. class D
  23. {
  24. public function index()
  25. {
  26. echo "这里是D类的index方法";
  27. }
  28. }
  29. interface PipelineInterface
  30. {
  31. public function pipe($middleware);
  32. public function then();
  33. }
  34. class Pipeline implements PipelineInterface
  35. {
  36. protected $Middleware = [];
  37. protected $request;
  38. public function __construct($object,$method,$argv = [])
  39. {
  40. $this->request['object'] = $object;
  41. $this->request['method'] = $method;
  42. $this->request['argv'] = $argv;
  43. }
  44. public function pipe($middleware)
  45. {
  46. $this->Middleware = $middleware;
  47. return $this;
  48. }
  49. public function then()
  50. {
  51. foreach ($this->Middleware as $value){
  52. call_user_func([$value,'handle'],$this->request);
  53. }
  54. return $this;
  55. }
  56. public function send()
  57. {
  58. $method = $this->request['method'];
  59. return $this->request['object']->$method(...$this->request['argv']);
  60. }
  61. }
  62. class Kernel
  63. {
  64. protected $Middleware = [];
  65. public function handle(Pipeline $pipeline)
  66. {
  67. return $pipeline->pipe($this->Middleware)
  68. ->then()
  69. ->send();
  70. }
  71. }
  72. class Http extends Kernel
  73. {
  74. protected $Middleware=[
  75. A::class,
  76. B::class,
  77. C::class
  78. ];
  79. }
  80. $httpKernel = (new Http())->handle(new Pipeline(new D(),'index'));

2.1.6 代理模式

给某一个对象提供一个代理,并由代理对象控制对原对象的引用

  1. interface I
  2. {
  3. public function boot();
  4. public function handle();
  5. }
  6. class A implements I
  7. {
  8. public function boot()
  9. {
  10. echo "A类的boot方法".PHP_EOL;
  11. }
  12. public function handle()
  13. {
  14. echo "A类的handle方法".PHP_EOL;
  15. }
  16. }
  17. class Proxy implements I
  18. {
  19. protected $A;
  20. public function __construct(I $i)
  21. {
  22. $this->A = $i;
  23. }
  24. public function boot()
  25. {
  26. $this->A->boot();
  27. }
  28. public function handle()
  29. {
  30. $this->A->handle();
  31. }
  32. }
  33. $Proxy = new Proxy(new A());
  34. $Proxy->boot();
  35. $Proxy->handle();
2.2 创建型模式
2.2.1 简单工厂模式

简单工厂的作用是实例化对象,而不需要客户了解这个对象属于哪个具体的子类。

  1. //mysql报错日志
  2. class MysqlLog
  3. {
  4. }
  5. //Redis报错日志
  6. class RedisLog
  7. {
  8. }
  9. //用户操作错误日志
  10. class UserLog
  11. {
  12. }
  13. //代码错诶日志
  14. class ErrorLog
  15. {
  16. }
  17. class Product
  18. {
  19. protected $Log;
  20. public function __construct(array $modules)
  21. {
  22. $factory = new LogFactory();
  23. foreach ($modules as $module){
  24. $this->Log[$module] = $factory->make($module);
  25. }
  26. }
  27. public function getLog()
  28. {
  29. return $this->Log;
  30. }
  31. }
  32. class LogFactory
  33. {
  34. public function make($abstract)
  35. {
  36. switch ($abstract){
  37. case 'mysql':
  38. return new MysqlLog();
  39. case 'redis':
  40. return new RedisLog();
  41. case 'user':
  42. return new UserLog();
  43. case 'error':
  44. return new ErrorLog();
  45. }
  46. }
  47. }
  48. $Product = new Product(array(
  49. 'mysql',
  50. 'redis',
  51. 'user',
  52. 'error'
  53. ));
  54. var_dump($Product->getLog());
2.2.2 Factory工厂模式

简单工厂模式的延伸,是在简单工厂的优点上去解决它的缺陷 

方法工厂模式的优点: 1.拥有良好的封装性,代码结构清晰 2. 拥有良好的扩展性 3. 屏蔽产品类

使用场景: 1. 日志记录 2. 多接口支付 3. 数据库连接封装

  1. interface LogInterface
  2. {
  3. public function log();
  4. }
  5. //mysql报错日志
  6. class MysqlLog implements LogInterface
  7. {
  8. public function log()
  9. {
  10. // TODO: Implement log() method.
  11. }
  12. }
  13. //Redis报错日志
  14. class RedisLog implements LogInterface
  15. {
  16. public function log()
  17. {
  18. // TODO: Implement log() method.
  19. }
  20. }
  21. //用户操作错误日志
  22. class UserLog implements LogInterface
  23. {
  24. public function log()
  25. {
  26. // TODO: Implement log() method.
  27. }
  28. }
  29. //代码错诶日志
  30. class ErrorLog implements LogInterface
  31. {
  32. public function log()
  33. {
  34. // TODO: Implement log() method.
  35. }
  36. }
  37. class Product
  38. {
  39. protected $Log;
  40. public function __construct()
  41. {
  42. $this->Log = array(
  43. (new MysqlLogFactory())->make(),
  44. (new RedisLogFactory())->make(),
  45. (new UserLogFactory())->make(),
  46. (new ErrorLogFactory())->make()
  47. );
  48. }
  49. public function getLog()
  50. {
  51. return $this->Log;
  52. }
  53. }
  54. interface LogFactory
  55. {
  56. public function make();
  57. }
  58. class MysqlLogFactory implements LogFactory
  59. {
  60. public function make()
  61. {
  62. return new MysqlLog();
  63. }
  64. }
  65. class RedisLogFactory implements LogFactory
  66. {
  67. public function make()
  68. {
  69. return new RedisLog();
  70. }
  71. }
  72. class UserLogFactory implements LogFactory
  73. {
  74. public function make()
  75. {
  76. return new UserLog();
  77. }
  78. }
  79. class ErrorLogFactory implements LogFactory
  80. {
  81. public function make()
  82. {
  83. return new ErrorLog();
  84. }
  85. }
  86. $product = new Product();
  87. var_dump($product->getLog());
2.2.3 抽象工厂模式

给客户端提供一个接口,可以创建多个产品族中的产品对象 

抽象工厂模式的优缺点: 1. 分离了具体的实现类 2. 增加替换工厂类目变的方便 3. 有利于统一同一类型的类目

  1. interface PayInterface
  2. {
  3. public function pay();
  4. }
  5. class AliPay implements PayInterface
  6. {
  7. public function pay()
  8. {
  9. return "支付宝支付";
  10. }
  11. }
  12. class TenPay implements PayInterface
  13. {
  14. public function pay()
  15. {
  16. return "微信支付";
  17. }
  18. }
  19. interface LogInterface
  20. {
  21. public function log();
  22. }
  23. class MysqlLog implements LogInterface
  24. {
  25. public function log()
  26. {
  27. return "记录mysql日志";
  28. }
  29. }
  30. class RedisLog implements LogInterface
  31. {
  32. public function log()
  33. {
  34. return "记录Redis日志";
  35. }
  36. }
  37. interface PayFactoryInterface
  38. {
  39. public function AliPayMake();
  40. public function TenPayMake();
  41. }
  42. interface LogFactoryInterface
  43. {
  44. public function MysqlLogMake();
  45. public function RedisLogMake();
  46. }
  47. class PayFactory implements PayFactoryInterface
  48. {
  49. public function AliPayMake()
  50. {
  51. return new AliPay();
  52. }
  53. public function TenPayMake()
  54. {
  55. return new TenPay();
  56. }
  57. }
  58. class LogFactory implements LogFactoryInterface
  59. {
  60. public function MysqlLogMake()
  61. {
  62. return new MysqlLog();
  63. }
  64. public function RedisLogMake()
  65. {
  66. return new RedisLog();
  67. }
  68. }
  69. class Order
  70. {
  71. protected $log;
  72. protected $pay;
  73. public function __construct()
  74. {
  75. $LogFactory = new LogFactory();
  76. $PayFactory = new PayFactory();
  77. $this->log = array(
  78. 'mysql' => $LogFactory->MysqlLogMake(),
  79. 'redis' => $LogFactory->RedisLogMake()
  80. );
  81. $this->pay = array(
  82. 'Ali' => $PayFactory->AliPayMake(),
  83. 'Ten' => $PayFactory->TenPayMake()
  84. );
  85. }
  86. public function getLog()
  87. {
  88. return $this->log;
  89. }
  90. public function getPay()
  91. {
  92. return $this->pay;
  93. }
  94. }
  95. $order = new Order();
  96. var_dump($order->getLog());
  97. var_dump($order->getPay());
2.2.4 Single单例模式

保证一个类只有一个实例,并提供一个访问它的全局访问点

使用场景: 1. 数据库连接 2. 日志操作类 3. 请求管理类 4. 配置管理类

  1. class Request
  2. {
  3. private static $request;
  4. protected $method;
  5. protected $uriPath;
  6. private function __construct(){}
  7. private function __clone(){}
  8. public static function getRequest()
  9. {
  10. if (self::$request == null){
  11. self::$request = new Request();
  12. }
  13. self::$request->method = $_SERVER['REQUEST_METHOD'];
  14. self::$request->uriPath= $_SERVER['REQUEST_URI'];
  15. return self::$request;
  16. }
  17. public function getMethod()
  18. {
  19. return $this->method;
  20. }
  21. public function getUriPath()
  22. {
  23. return $this->uriPath;
  24. }
  25. public function isMethod($method):bool
  26. {
  27. return $this->method === strtoupper($method);
  28. }
  29. }
  30. $request = Request::getRequest();
  31. var_dump($request->isMethod('get'));
2.3 行为型模式
2.3.1 策略模式

定义一系列的算法,把它们一个个封装起来,并且使它们可以相互替换

策略模式使用的业务场景: 1. 短语发送 2. 多支付接口 3. 日志记录  

  1. interface PayInterface
  2. {
  3. public function pay();
  4. }
  5. class AliPay implements PayInterface
  6. {
  7. public function pay()
  8. {
  9. echo "支付宝支付";
  10. }
  11. }
  12. class TenPay implements PayInterface
  13. {
  14. public function pay()
  15. {
  16. echo "微信支付";
  17. }
  18. }
  19. class Pay
  20. {
  21. protected $pay;
  22. public function __construct(PayInterface $pay)
  23. {
  24. $this->pay = $pay;
  25. }
  26. public function getPay()
  27. {
  28. return $this->pay;
  29. }
  30. }
  31. $pay = new Pay(new AliPay());
  32. $pay->getPay()->pay();
2.3.2 Observe观察者模式

多个对象间存在一对多的依赖关系,当一个对象的状态 发生改变时,所有依赖于它的对象都得到通知并被自动更新

观察者模式的使用场景: 1. 订单支付场景 2. 发布订阅类型的功能

观察者模式的优点: 1. 观察者与被观察者依赖于抽象 2. 观察者符合开闭原则,只要符合接口,就能够进行扩展

观察者模式的缺点: 1. 依赖于接口的关系,具备一定的局限性 2. 过多的观察者,代码运行消耗可能会很大

  1. interface OrderPayInterface
  2. {
  3. public function PayEvent($OrderId = null);
  4. }
  5. class OrderPay implements OrderPayInterface
  6. {
  7. public function PayEvent($OrderId = null)
  8. {
  9. echo "订单ID为:{$OrderId}的订单状态为已支付".PHP_EOL;
  10. }
  11. }
  12. abstract class OrderEventAbstract
  13. {
  14. private $Observer;
  15. public function register(OrderPayInterface $pay)
  16. {
  17. $this->Observer = $pay;
  18. }
  19. public function notify($OrderId)
  20. {
  21. $this->Observer->PayEvent($OrderId);
  22. }
  23. }
  24. class Order extends OrderEventAbstract
  25. {
  26. public function pay($OrderId)
  27. {
  28. echo "支付成功".PHP_EOL;
  29. $this->notify($OrderId);
  30. }
  31. }
  32. $order = new Order();
  33. $order->register(new OrderPay());
  34. $order->pay(1);
2.3.3 命令链模式

以松散耦合主题为基础,发送消息、命令和请求,或通过一组处理 程序发送任意内容

命令链模式的应用场景: 1. 登录注册不同角色的业务操作 2. 直播间不同等级会员业务 3. 订单支付状态

  1. interface CommandInterface
  2. {
  3. public function runCommand($name,$argv);
  4. }
  5. class CreateControllerCommand implements CommandInterface
  6. {
  7. public function runCommand($name, $argv)
  8. {
  9. echo "创建控制器".PHP_EOL;
  10. }
  11. }
  12. class CreateModelCommand implements CommandInterface
  13. {
  14. public function runCommand($name, $argv)
  15. {
  16. echo "创建模型".PHP_EOL;
  17. }
  18. }
  19. class Command
  20. {
  21. private $command = [];
  22. public function register(array $command)
  23. {
  24. $this->command = $command;
  25. }
  26. public function run($name,$argv)
  27. {
  28. foreach ($this->command as $key=>$value){
  29. if ($name == $key){
  30. return $value->runCommand($name,$argv);
  31. }
  32. }
  33. }
  34. }
  35. $command = new Command();
  36. $command->register(array(
  37. 'controller' => new CreateControllerCommand(),
  38. 'model' => new CreateModelCommand()
  39. ));
  40. $command->run('model',1);
  41. interface RoleLoginInterface
  42. {
  43. public function handle($name);
  44. }
  45. class bronze implements RoleLoginInterface
  46. {
  47. public function handle($name)
  48. {
  49. echo "欢迎{$name}进入直播间".PHP_EOL;
  50. }
  51. }
  52. class silver implements RoleLoginInterface
  53. {
  54. public function handle($name)
  55. {
  56. echo "欢迎白银会员{$name}进入直播间".PHP_EOL;
  57. }
  58. }
  59. class gold implements RoleLoginInterface
  60. {
  61. public function handle($name)
  62. {
  63. echo "欢迎黄金大神{$name}进入直播间,此时有掌声与音乐".PHP_EOL;
  64. }
  65. }
  66. class Role
  67. {
  68. private $role = [];
  69. public function register(array $role)
  70. {
  71. $this->role = $role;
  72. }
  73. public function LoginEvent($name,$role)
  74. {
  75. foreach ($this->role as $key => $value){
  76. if ($role == $key){
  77. return $value->handle($name);
  78. }
  79. }
  80. }
  81. }
  82. $role = new Role();
  83. $role->register(array(
  84. 'bronze' => new bronze(),
  85. 'silver' => new silver(),
  86. 'gold' => new gold()
  87. ));
  88. $role->LoginEvent('harry','bronze');
  89. $role->LoginEvent('xx','gold');
  90. $role->LoginEvent('lori','silver');
2.3.4 迭代器模式

提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该 对象的内部显示

迭代器模式的角色: 1. 迭代器:迭代器定义访问和遍历元素的接口 2. 具体迭代器: 实现迭代器接口,对该聚合遍历时跟踪当前位置 3. 聚合: 聚合实现创建相应迭代器的接口,这个操作是返回具体迭代器的实例

迭代器的优点: 1.多种遍历方式 2.简化聚合类 3.为不同的集合提供统一的接口

迭代器的缺点: 迭代器模式将存储数据和遍历数据的职责分离增加新的集合对象时需要增加 对应的迭代器类,类的个数成对增加,在一定程度上增加系统复杂度

使用场景: 1.访问一个聚合对象的内容而无需暴露它的内部表示 2.支持对聚合对象的多种遍历 3.为遍历不同的聚合结构提供一个统一的接口

  1. class CycleIterator implements Iterator
  2. {
  3. private $array = [];
  4. private $currentIndex = 0;
  5. public function __construct($array)
  6. {
  7. $this->array = $array;
  8. }
  9. public function current()
  10. {
  11. return $this->array[$this->currentIndex];
  12. }
  13. public function setCurrentIndex($currentIndex)
  14. {
  15. $this->currentIndex = $currentIndex;
  16. }
  17. public function setArray($array)
  18. {
  19. $this->array = $array;
  20. }
  21. public function getCurrentIndex()
  22. {
  23. return $this->currentIndex;
  24. }
  25. public function getArray()
  26. {
  27. return $this->array;
  28. }
  29. public function key()
  30. {
  31. return $this->currentIndex;
  32. }
  33. public function next()
  34. {
  35. ++$this->currentIndex;
  36. }
  37. public function rewind()
  38. {
  39. $this->currentIndex = 0;
  40. }
  41. public function valid()
  42. {
  43. return isset($this->array[$this->currentIndex]);
  44. }
  45. }
  46. class Cycle implements IteratorAggregate
  47. {
  48. protected $array;
  49. public function __construct($array)
  50. {
  51. $this->array = $array;
  52. }
  53. public function getIterator()
  54. {
  55. return new CycleIterator($this->array);
  56. }
  57. }
  58. $list = [1,2,3,4,5,6,7,8,9];
  59. $cycle= new CycleIterator($list);
  60. foreach ($cycle as $value){
  61. echo $value.PHP_EOL;
  62. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/332293
推荐阅读
相关标签
  

闽ICP备14008679号