<?php interface Cache { public function set($key, $value); public function get($key); public function delete($key); } class Memcache implements Cache { public function set($key, $value) { // TODO: Implement set() method. echo $key . '-' . $value; } public function get($key) { // TODO: Implement get() method. echo $key; } public function delete($key) { // TODO: Implement delete() method. echo $key; } } class CacheFactory { public static function factory(Cache $cache) { return $cache; } } $cache = CacheFactory::factory(new Memcache()); $cache->set('nihao', 123);
是这样的,工厂设计模式只是让代码更容易扩展和维护,比如你缓存要修改成Redis,只用在加一个Redis类,里面实现set、get、delete方法,然后修改39行代码为 $cache
= CacheFactory::factory(
new
Redis()),对于代码中调用缓存的地方就不用所有地方去修改了。