码迷,mamicode.com
首页 > 其他好文 > 详细

AbstractFactory(抽象工厂模式)

时间:2017-07-04 12:18:22      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:php   print   不同的   imp   func   class   rom   getname   return   

AbstractFactory(抽象工厂模式)

  有些情况下我们需要根据不同的选择逻辑提供不同的构造工厂,而对于多个工厂而言需要一个统一的抽象

<?php
 
class Config {
    public static $factory = 1;
}
 
interface Product {
    public function getName();
}
 
abstract class AbstractFactory {
 
    public static function getFactory() {
        switch (Config::$factory) {
            case 1:
                return new FirstFactory();
            case 2:
                return new SecondFactory();
        }
        throw new Exception(‘Bad config‘);
    }
 
    abstract public function getProduct();
}
 
class FirstFactory extends AbstractFactory {
    public function getProduct() {
        return new FirstProduct();
    }
}
class FirstProduct implements Product {
    public function getName() {
        return ‘The product from the first factory‘;
    }
}
 
class SecondFactory extends AbstractFactory {
    public function getProduct() {
        return new SecondProduct();
    }
}
class SecondProduct implements Product {
    public function getName() {
        return ‘The product from second factory‘;
    }
}
 
$firstProduct = AbstractFactory::getFactory()->getProduct();
Config::$factory = 2;
$secondProduct = AbstractFactory::getFactory()->getProduct();
 
print_r($firstProduct->getName());
// The first product from the first factory
print_r($secondProduct->getName());
// Second product from second factory

  

AbstractFactory(抽象工厂模式)

标签:php   print   不同的   imp   func   class   rom   getname   return   

原文地址:http://www.cnblogs.com/Czc963239044/p/7115773.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!