Adapter
8/8/25About 1 min
Description
Adapter is a structural design pattern, which allows incompatible objects to collaborate.
- Kết nối các object độc lập làm việc với nhau.
Example
Code
Xử lí cache (kết hợp abstract factory và adapter)
abstract class AdapterFactory
{
abstract public function getInstance(): AdapterInterface;
}
interface AdapterInterface
{
public function get(string $key);
public function set(string $key, $value, $expireAt = null);
public function has(string $key): bool;
}
class Cache implements AdapterInterface
{
private AdapterInterface $adapter;
public function __construct(AdapterInterface $adapter)
{
$this->adapter = $adapter;
}
public function getAdapter()
{
return $this->adapter;
}
public function setAdapter($adapter)
{
$this->adapter = $adapter;
}
public function get(string $key)
{
return $this->adapter->get($key);
}
public function set(string $key, $value, $expireAt = null)
{
return $this->adapter->set($key, $value, $expireAt);
}
public function has(string $key): bool
{
return $this->adapter->has($key);
}
}
class MemcachedFactory extends AdapterFactory
{
private string $host;
private string $port;
public function __construct(string $host = "localhost", string $port = "11211")
{
$this->host = $host;
$this->port = $port;
}
public function getInstance(): AdapterInterface
{
return new LibMemcached($this->host, $this->port);
}
}
class LibMemcached implements AdapterInterface
{
private \Memcached $memcache;
public function __construct(string $host, string $port)
{
$this->memcache = $this->getMemcache();
$this->memcache->addServer($host, $port);
}
protected function getMemcache(): \Memcached
{
return new \Memcached();
}
public function get(string $key)
{
return $this->memcache->get($key);
}
public function set(string $key, $value, $expireAt = null)
{
return $this->memcache->set($key, $value, $expireAt);
}
public function has(string $key): bool
{
return $this->memcache->get($key);
}
}
- Dùng Adapter Pattern để liên kết Cache và Memcache.
- Memcache đang dùng Abstract Factory, nếu sau này maintance hoặc sử dụng 1 driver khác (redis, db, file,..) để dùng lưu cache thì cũng dễ dàng và không cần thay đổi Cache theo AdapterInterface ban đầu.