auto commit
This commit is contained in:
parent
c6ef4e10fc
commit
dc3c4cd4ee
@ -451,7 +451,7 @@ public class Client {
|
||||
|
||||
### JDK
|
||||
|
||||
- [java.lang.Object#clone()] (http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#clone%28%29)
|
||||
- [java.lang.Object#clone()](http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#clone%28%29)
|
||||
|
||||
# 三、行为型
|
||||
|
||||
@ -621,7 +621,77 @@ public class Client {
|
||||
|
||||
### 意图
|
||||
|
||||
定义一系列算法,封装每个算法,并使它们可以互换。策略可以让算法独立于使用它的客户端。
|
||||
定义一系列算法,封装每个算法,并使它们可以互换。
|
||||
|
||||
策略模式可以让算法独立于使用它的客户端。
|
||||
|
||||
### 类图
|
||||
|
||||
- Strategy 接口定义了一个算法族,它们都具有 BehaviorInterface() 方法。
|
||||
- Context 是使用到该算法族的类,其中的 doSomething() 方法会调用 BehaviorInterface(),setStrategy(in Strategy) 方法可以动态地改变 strategy 对象,也就是说能动态地改变 Context 所使用的算法。
|
||||
|
||||
<div align="center"> <img src="../pics//4dc08713-f6fe-424c-a24c-ad5a993a941d.png"/> </div><br>
|
||||
|
||||
### 实现
|
||||
|
||||
设计一个鸭子,它可以动态地改变叫声。这里的算法族是鸭子的叫声行为。
|
||||
|
||||
```java
|
||||
public interface QuackBehavior {
|
||||
void quack();
|
||||
}
|
||||
```
|
||||
|
||||
```java
|
||||
public class Quack implements QuackBehavior {
|
||||
@Override
|
||||
public void quack() {
|
||||
System.out.println("quack!");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```java
|
||||
public class Squeak implements QuackBehavior{
|
||||
@Override
|
||||
public void quack() {
|
||||
System.out.println("squeak!");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```java
|
||||
public class Duck {
|
||||
private QuackBehavior quackBehavior;
|
||||
|
||||
public void performQuack() {
|
||||
if (quackBehavior != null) {
|
||||
quackBehavior.quack();
|
||||
}
|
||||
}
|
||||
|
||||
public void setQuackBehavior(QuackBehavior quackBehavior) {
|
||||
this.quackBehavior = quackBehavior;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```java
|
||||
public class Client {
|
||||
public static void main(String[] args) {
|
||||
Duck duck = new Duck();
|
||||
duck.setQuackBehavior(new Squeak());
|
||||
duck.performQuack();
|
||||
duck.setQuackBehavior(new Quack());
|
||||
duck.performQuack();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```html
|
||||
squeak!
|
||||
quack!
|
||||
```
|
||||
|
||||
### JDK
|
||||
|
||||
|
BIN
pics/4dc08713-f6fe-424c-a24c-ad5a993a941d.png
Normal file
BIN
pics/4dc08713-f6fe-424c-a24c-ad5a993a941d.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 16 KiB |
Loading…
x
Reference in New Issue
Block a user