public interface Authorization {
String getToken();
}
还有:
// goes to the DB and gets a token for example
public class DBAuthorization implements Authorization {
@Override
public String getToken() {
return "DB-Token";
}
}
还有这个 Authorization的呼叫者,一个非常愚蠢的呼叫者:
class Caller {
void authenticatedUserAction(Authorization authorization) {
System.out.println("doing some action with : " + authorization.getToken());
}
}
public interface JobSeeker {
int interviewScore();
}
以及如何实施:
class Newbie implements JobSeeker {
@Override
public int interviewScore() {
return 10;
}
}
现在我们想要增加一个更有经验的候选人,加上面试成绩和另一个 JobSeeker的成绩:
@RequiredArgsConstructor
public class TwoYearsInTheIndustry implements JobSeeker {
private final JobSeeker jobSeeker;
@Override
public int interviewScore() {
return jobSeeker.interviewScore() + 20;
}
}
public class TwoYearsInTheIndustry implements JobSeeker {
private final Newbie newbie = new Newbie();
@Override
public int interviewScore() {
return newbie.interviewScore() + 20;
}
}
interface CarRepositoryInterface
{
public function getById(int $id) : Car
}
class CarRepository implements CarRepositoryInterface
{
public function getById(int $id) : Car
{
sleep(3); //... fake some heavy db call
$car = new Car;
$car->setId($id);
$car->setName("Mercedes Benz");
return $car;
}
}
CarRepository-Proxy
Proxy通常用作延迟加载或缓存代理:
class CarRepositoryCacheProxy implements CarRepositoryInterface
{
private $carRepository;
private function getSubject() : CarRepositoryInterface
{
if($this->carRepository == null) {
$this->carRepository = new CarRepository();
}
return $this->carRepository;
}
/**
* This method controls the access to the subject
* based on if there is cache available
*/
public function getById(int $id) : Car
{
if($this->hasCache(__METHOD__)) {
return unserialize($this->getCache(__METHOD__));
}
$response = $this->getSubject()->getById($id);
$this->writeCache(__METHOD__, serialize($response));
return $response;
}
private function hasCache(string $key) : bool
{
//... implementation
}
private function getCache(string $key) : string
{
//... implementation
}
private function writeCache(string $key, string $result) : string
{
//... implementation
}
}
CarRepository-Decorator
只要所添加的行为不“控制”主体,就可以使用 Decorator:
class CarRepositoryEventManagerDecorator implements CarRepositoryInterface
{
private $subject, $eventManager;
/**
* Subjects in decorators are often passed in the constructor,
* where a proxy often takes control over the invocation behavior
* somewhere else
*/
public function __construct(CarRepositoryInterface $subject, EventManager $eventManager)
{
$this->subject = $subject;
$this->eventManager = $eventManager;
}
public function getById(int $id) : Car
{
$this->eventManager->trigger("pre.getById");
//this method takes no control over the subject
$result = $this->subject->getById($id);
$this->eventManager->trigger("post.getById");
return $result;
}
}