工厂模式以及工厂方法

来源:互联网 发布:淘宝好听的用户名大全 编辑:程序博客网 时间:2024/06/09 16:46

2、工厂

接口中定义一些方法

实现接口的类实现这些方法

工厂类:用于实例化对象

优点:为系统结构提供了灵活的动态扩展机制,方便维护

3、工厂方法

工厂方法模式核心就是工厂类不在负责所有对象的创建,而是将具体创建的工作交给子类去做,成为了一个抽象工厂角色,他仅负责给出具体工厂类必须实现的接口,而不接触哪一个产品类应当被实例化这种细节


工厂模式代码:

<?phpinterface Skill{function family();function buy();}class Person implements Skill{function family(){echo '人族在辛苦的伐木<br/>';}function buy(){echo '人族在使用钱买房子<br/>';}}class JingLing implements Skill{function family(){echo '精灵族在坎木<br/>';}function buy(){echo '精灵在使用精灵币<br/>';}}class factory{static function createHero($type){switch($type){case 'person':return new Person();break;case 'jingling':return new JingLing();break;}}}$person=factory::createHero('person');$jing=factory::createHero('jingling');$person->family();?>
工厂方法代码:

<?phpinterface Tell{function call();function receive();}class XiaoMi implements Tell{function call(){echo '我在使用小米手机打电话';}function receive(){echo '我在使用小米手机接电话';}}class HuaWei implements Tell{function call(){echo '我在使用华为手机';}function receive(){echo '我在使用华为手机接电化';}}interface Factory{static function createPhone();}class XiaoFactory implements Factory{static function createPhone(){return new XiaoMi();}}class HuaWeiFactory implements Factory{static function createPhone(){return new HuaWei();}}$xiaomi=XiaoFactory::createPhone();$xiaomi->call();?>