Created
May 17, 2018 08:29
-
-
Save HavenShen/864c3f1e661b72b72ac9c7a6ce4501ae to your computer and use it in GitHub Desktop.
Open/Closed Principle (OCP).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Bad demo | |
$paypal = new Paypal(); | |
$paymentManager = new PaymentManager($paypal); | |
$paymentManager->process(); | |
class PaymentManager | |
{ | |
protected $paypal; | |
public function __construct(Paypal $paypal) | |
{ | |
$this->paypal = $paypal; | |
} | |
public function process() | |
{ | |
$this->paypal->processPayment(); | |
// ...and other payment stuff | |
} | |
} | |
class Paypal | |
{ | |
public function processPayment() | |
{ | |
// ...process the payment with PayPal | |
} | |
} | |
// Good demo | |
$paypal = new Paypal(); | |
$creditCard = new CreditCard(); | |
$paymentManager = new PaymentManager($paypal); | |
$paymentManager->process(); | |
class PaymentManager | |
{ | |
protected $paymentMethod; | |
public function __construct(PaymentMethodInterface $paymentMethod) | |
{ | |
$this->paymentMethod = $paymentMethod; | |
} | |
public function process() | |
{ | |
$this->paymentMethod->processPayment(); | |
// ...and other payment stuff | |
} | |
} | |
interface PaymentMethodInterface | |
{ | |
public function processPayment(); | |
} | |
class Paypal implements PaymentMethodInterface | |
{ | |
public function processPayment() | |
{ | |
// ...process the payment with PayPal | |
} | |
} | |
class CreditCard implements PaymentMethodInterface | |
{ | |
public function processPayment() | |
{ | |
// ...process the payment with PayPal | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment