php工厂模式

来源:互联网 发布:ios9越狱mac 编辑:程序博客网 时间:2024/06/08 18:28
简单工厂模式(Simple Factory Pattern)又被称为静态工厂方法模式(Static Factory Method Pattern),具体指创建一个类似于工厂的类,通过对该类中成员方法的调用返回不同类型的对象。
<?phpheader('content-type:text/html;charset=utf-8');//人类接口interface people{function say();}//student类class student implements people{public function say(){echo "我是学生";}}//工人类class worker implements people{public function say(){echo "我是工人";}}//简单工厂类class factory{static function createstudent(){return new student();}static function createworker(){return new worker();}}
工厂方法:定义一个用于创建对象的接口,让子类决定哪个类实例化。 他可以解决简单工厂模式中的封闭开放原则问题。
<?phpheader('content-type:text/html;charset=utf-8');//人类接口interface people{function say();}//student类class student implements people{public function say(){echo "我是学生";}}//工人类class worker implements people{public function say(){echo "我是工人";}}//简单工厂类class factory{static function createstudent(){return new student();}static function createworker(){return new worker();}}interface createPeople{public function create();}class FactoryStudent implements createPeople{public function create(){return new student();}}class FactoryWoker implements createPeople{public function create(){return new worker();}}class Client{public function test(){$factory=new FactoryStudent();$man=$factory->create();$man->say();$factory=new FactoryWoker();$man=$factory->create();$man->say();}}$demo = new Client;$demo->test();?>


0 0
原创粉丝点击