• 工厂模式


    简单工厂

     1 <?php
     2 
     3 /**
     4  * 好处是当Person对象变化时, 只需要把这个工厂变一下就成了, 不用到每个Person对象那里去改变每一个new Person
     5  */
     6 class SimpleFactory
     7 {
     8     /**
     9      * 这里可以写switch($name)实现对对象的创建, 这里为了简单,省略了
    10      * @return Person
    11      */
    12     public function produce()
    13     {
    14         return new Person();
    15     }
    16 }
    17 
    18 class Person
    19 {
    20     public function test()
    21     {
    22         echo "I'm test";
    23     }
    24 }
    25 
    26 $p = (new SimpleFactory())->produce()->test();
    View Code

    静态工厂

     

     1 <?php
     2 
     3 /**
     4  * 好处是当Person对象变化时, 只需要把这个工厂变一下就成了, 不用到每个Person对象那里去改变每一个new Person
     5  */
     6 class StaticFactory
     7 {
     8     /**
     9      * 这里可以写switch($name)实现对对象的创建, 这里为了简单,省略了
    10      * @return Person
    11      */
    12     public static function produce()
    13     {
    14         return new Person();
    15     }
    16 }
    17 
    18 class Person
    19 {
    20     public function test()
    21     {
    22         echo "I'm test";
    23     }
    24 }
    25 
    26 $p = StaticFactory::produce()->test();
    View Code

    工厂方法

    工厂方法与抽象工厂的区别:
    工厂方法: 抽象出一个共同的创建的行为, 但具体能创建出来什么东西,是由具体的工厂来实现的
    抽象模式: 抽象出共同的创建行为,还有必须创建的对象, 所有的工厂都必须实现

     

     1 <?php
     2 /**
     3  * 工厂方法与抽象工厂的区别:
     4  * 工厂方法: 抽象出一个共同的创建的行为, 但具体能创建出来什么东西,是由具体的工厂(子类或实现类)来实现的
     5  * 抽象模式: 抽象出共同的创建行为,还有必须创建的对象, 所有的工厂(子类或实现类)都必须实现
     6  */
     7 
     8 abstract class FactoryMethod
     9 {
    10     abstract function produce($productName);
    11 }
    12 
    13 class FactoryA extends FactoryMethod
    14 {
    15     function produce($productName)
    16     {
    17         switch ($productName) {
    18             case "A":
    19                 return new ProductA();
    20             
    21             case "B":
    22                 return new ProductB();
    23             
    24             default:
    25                 echo "no products";
    26                 break;
    27         }
    28     }
    29 }
    30 
    31 class FactoryB extends FactoryMethod
    32 {
    33     function produce($productName)
    34     {
    35         return new ProductA();
    36     }
    37 }
    38 
    39 
    40 
    41 
    42 class ProductA
    43 {
    44 
    45 }
    46 
    47 class ProductB
    48 {
    49 
    50 }
    View Code
  • 相关阅读:
    hdu4059 The Boss on Mars
    cf475D CGCDSSQ
    HDU
    cf1447D Catching Cheaters
    cf1440 Greedy Shopping
    Treats for the Cows
    dp废物学会了记录路径
    D. Jzzhu and Cities
    cf1359D Yet Another Yet Another Task
    关于sg函数打表的理解
  • 原文地址:https://www.cnblogs.com/hangtt/p/6257223.html
Copyright © 2020-2023  润新知