Skip to content

Instantly share code, notes, and snippets.

@Shipu
Created Jul 28, 2021
Embed
What would you like to do?
Strategy Pattern
<?php
interface Coffee
{
public function make();
}
class Cappuccino implements Coffee
{
public function make()
{
var_dump("this is cappuccino..");
}
}
class Latte implements Coffee
{
public function make()
{
var_dump("this is hazel nut latte..");
}
}
class BlackCoffee implements Coffee
{
public function make()
{
var_dump("this is black coffee..");
}
}
class Application
{
public function makeCoffee(Coffee $coffee)
{
return $coffee->make();
}
}
$app = new Application();
$app->makeCoffee(new Latte());
$app->makeCoffee(new Cappuccino());
$app->makeCoffee(new BlackCoffee());
<?php
interface Logger
{
public function log($data);
}
class DatabaseLogger implements Logger
{
public function log($data)
{
var_dump("this is database log");
var_dump($data);
}
}
class FileLogger implements Logger
{
public function log($data)
{
var_dump("this is file log");
var_dump($data);
}
}
class WebServiceLogger implements Logger
{
public function log($data)
{
var_dump("this is web service log");
var_dump($data);
}
}
class Application
{
public function log($data, Logger $logger = null)
{
$logger = $logger ?: new ConsoleLogger();
return $logger->log($data);
}
}
$app = new Application();
$app->log("log data", new FileLogger());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment