你应该看看这本书Design Patterns: Elements of Reusable Object-Oriented Software
的问题正如你发现的那样,使可扩展类将系统分解为有用的和可重用的对象。
由于许多因素起作用:封装,粒度,依赖性,灵活性,性能,进化,可重用性等等,这项任务很困难。
您是试图模拟一些真实世界的场景,还是您专注于应用程序内的通信/协作和依赖关系?
这里有一个例子,我认为有点演示你在找什么。当然还有更好的例子:
我想开发一个缓存系统,为我的开发人员提供一个简单的,规范化的API,无论他们在什么地方缓存什么东西。我想在缓存系统中(基本级别)做什么?
- 我希望能够缓存的东西(套)
- 我希望能够取回的东西(获取)
- 我希望能够缓存失效(删除)
我想出了这一点:
abstract class MyNs_Cache
{
abstract public function Set($key, $data, $ttl);
abstract public function Get($key);
abstract public function Delete($key, $ttl);
}
有我的可扩展基类。然后我有三个缓存类MyNs_Cache_Fs
,MyNs_Cache_Apc
和MyNs_Cache_Memcache
class MyNs_Cache_Fs
{
...
public function Set($key, $data, $ttl)
{
// here I use fopen/fwrite/etc. to create the cached data
}
public function Get($key)
{
// here I retrieve the file from the filesystem (if it exists)
}
public function Delete($key) { ... }
}
这是相当直截了当。它根据FileSystem实现缓存。它不会提供任何超过我原来的课程的东西。
class MyNs_Cache_Apc
{
...
public function Set($key, $data, $ttl)
{
return apc_add($key, $data, $ttl); // NOT A FILESYSTEM CALL
}
public function Get($key) { ... } // you get the idea.
// This is specific to APC, so I add the functionality HERE
// NOT in my main Caching class.
public function PurgeCache()
{
return apc_clear_cache();
}
}
我的APC缓存做的一切,我想在缓存系统(设置/获取/删除),但它同时也提供清除整个缓存(东西是不适合我的文件系统缓存有用,并与memcached的是不可能的)的能力
class MyNs_Cache_Memcache
{
// Memcached needs a pool of servers. APC and filesystem don't.
private $servers = array(..);
// It also uses a memcached object.
private $conn;
public function __construct()
{
$this->conn = new Memcached;
foreach ($this->$servers as $server)
$this->AddServer($server);
}
... // we do all the standard stuff using memcached methods
// We also want to be able to manage our connection pool
public function AddServer($server)
{
$this->conn->addServer(...);
}
// And in some cases, we use inc/dec from memcached
// APC doesn't have this, and it makes little sense in a filesystem
public function Increment($key) { ... }
}
现在我知道,我总是可以得到我的缓存中的对象之一,只是在$ obj->获取(“some_key”),我将永远得到一个结果。
同样,我也可以访问我目前正在尝试使用的功能。