你应该看看这本书设计模式:可重用的面向对象软件的元素
正如您所发现的,制作可扩展类的问题在于将系统分解为有用且可重用的对象。
这项任务很困难,因为许多因素都在起作用:封装、粒度、依赖性、灵活性、性能、演进、可重用性等等。
您是在尝试模拟一些真实世界的场景,还是专注于应用程序内部的通信/协作和依赖关系?
这是一个我认为有点展示你正在寻找的例子的例子。当然还有更多更好的例子:
我想开发一个缓存系统,为我的开发人员提供一个简单、规范化的 API,无论他们在什么地方/在哪里缓存东西。我在缓存系统中想要什么(在基本级别)?
- 我希望能够缓存一些东西(设置)
- 我希望能够检索到那个东西(get)
- 我希望能够使缓存无效(删除)
我想出了这个:
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) { ... }
}
这是相当直截了当的。它根据文件系统实现缓存。它没有提供任何超出我原来的课程的东西。
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->Get('some_key') 就可以得到结果。
同样,我也可以访问特定于我当前正在尝试使用的功能。