运用共享技术有效的支持大量细粒度的对象
    享元,就是分享元素的意思,跟注册当时的意思差不多,注册到一个容器中,这个是保存在享元工厂中,有就返回,没有就实例化然后返回,
    一般池技术就是享元模式的重要实现方式,string常量池,数据库连接池,缓冲池等,

    有对象的外部状态跟内部状态,内部状态时确定这个类的,共享,不能修改,外部状态就是参数,不共享能修改,
    一个类实例化之后,放在享元工厂中,通过内部状态判断,
    image.png

    1. <?php
    2. /**
    3. * 接口类
    4. */
    5. interface Flyweight
    6. {
    7. public function operation($extrinsicState): void;
    8. }
    9. /**
    10. * 接口实现类共享
    11. */
    12. class ConcreteFlyweight implements Flyweight
    13. {
    14. //内部状态,共享
    15. private $template;
    16. function __construct($temp)
    17. {
    18. //实例化确定
    19. $this->template = $temp;
    20. }
    21. //外部状态不共享
    22. public function operation($extrinsicState): void
    23. {
    24. echo $this->template . '方棋子方位:' . $extrinsicState . PHP_EOL;
    25. }
    26. }
    27. /**
    28. * 接口实现类不共享
    29. */
    30. class UnsharedConcreteFlyweight implements Flyweight
    31. {
    32. //内部状态,共享
    33. private $template;
    34. function __construct($temp)
    35. {
    36. //实例化确定
    37. $this->template = $temp;
    38. }
    39. //外部状态不共享
    40. public function operation($extrinsicState): void
    41. {
    42. echo $this->template . '方棋子方位:' . $extrinsicState . PHP_EOL;
    43. }
    44. }
    45. /**
    46. * 享元工厂
    47. */
    48. class FlyweightFactory
    49. {
    50. private $flyweights;
    51. public function getFlyweight($key)
    52. {
    53. if (!array_key_exists($key, $this->flyweights)) {
    54. echo '创建实例:' . $key . PHP_EOL;
    55. $this->flyweights[$key] = new ConcreteFlyweight($key);
    56. }
    57. echo '拿到实例:' . $key . PHP_EOL;
    58. return $this->flyweights[$key];
    59. }
    60. public function count()
    61. {
    62. echo '实例数量:' . count($this->flyweights) . PHP_EOL;
    63. }
    64. }
    65. //实例化享元工厂
    66. $factory = new FlyweightFactory();
    67. //获取一个实例
    68. $flA = $factory->getFlyweight('黑');
    69. $flA->operation('七右之十四');
    70. $factory->count();
    71. $flA = $factory->getFlyweight('黑');
    72. $flA->operation('七右之六');
    73. $factory->count();
    74. //获取一个实例
    75. $flA = $factory->getFlyweight('白');
    76. $flA->operation('六右之三');
    77. $factory->count();
    78. $flA = $factory->getFlyweight('白');
    79. $flA->operation('六右之六');
    80. $factory->count();
    81. //非共享
    82. $Unshared = new UnsharedConcreteFlyweight('彩');
    83. $Unshared->operation('六右之六');