-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathbehavioral-strategy.php
More file actions
82 lines (72 loc) · 2.02 KB
/
behavioral-strategy.php
File metadata and controls
82 lines (72 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
/**
* This example just to simulate how Strategy can be work
* 2nees.com
*/
/**
* Interface EncryptStrategy - Strategy interface - Declare method to share it in all Concrete Strategy which call in context
*/
interface EncryptStrategy {
public function encrypt($text): string;
}
/**
* Class EncryptedContext - This is the Context class, which its Reference to one of Concrete Strategy Class
** and communicate is done via Strategy interface
*/
class EncryptedContext {
private EncryptStrategy $encryptStrategy;
private string $text;
/**
* EncryptedContext constructor.
* @param EncryptStrategy $encryptStrategy
*/
public function __construct(EncryptStrategy $encryptStrategy)
{
$this->encryptStrategy = $encryptStrategy;
}
public function encryptText(): void {
echo $this->encryptStrategy->encrypt($this->text) . PHP_EOL;
}
/**
* @param string $text
*/
public function setText(string $text): void
{
$this->text = $text;
}
/**
* @param EncryptStrategy $encryptStrategy
*/
public function setEncryptStrategy(EncryptStrategy $encryptStrategy): void
{
$this->encryptStrategy = $encryptStrategy;
}
}
#region Concrete Strategy - these class will implement different variations of encrypt
class MD5Encrypt implements EncryptStrategy {
public function encrypt($text): string
{
return "MD5: " . md5($text);
}
}
class SHA1Encrypt implements EncryptStrategy {
public function encrypt($text): string
{
return "SHA1: " . sha1($text);
}
}
class Haval160Encrypt implements EncryptStrategy {
public function encrypt($text): string
{
return "haval160,4: " . hash("haval160,4", $text);
}
}
#endregion
// Client...
$encrypt = new EncryptedContext(new SHA1Encrypt());
$encrypt->setText("2nees.com");
$encrypt->encryptText();
$encrypt->setEncryptStrategy(new MD5Encrypt());
$encrypt->encryptText();
$encrypt->setEncryptStrategy(new Haval160Encrypt());
$encrypt->encryptText();