auto commit
This commit is contained in:
parent
499d369db3
commit
d361bc608a
|
@ -2631,7 +2631,6 @@ public class SubSystem {
|
|||
public class Facade {
|
||||
private SubSystem subSystem = new SubSystem();
|
||||
|
||||
|
||||
public void watchMovie() {
|
||||
subSystem.turnOnTV();
|
||||
subSystem.setCD("a movie");
|
||||
|
@ -2657,7 +2656,79 @@ public class Client {
|
|||
|
||||
### 意图
|
||||
|
||||
利用共享的方式来支持大量的对象,这些对象一部分内部状态是相同的,而另一份状态可以变化。
|
||||
利用共享的方式来支持大量细粒度的对象,这些对象一部分内部状态是相同的。
|
||||
|
||||
### 类图
|
||||
|
||||
- Flyweight:享元对象
|
||||
- IntrinsicState:内部状态,相同的项元对象共享
|
||||
- ExtrinsicState:外部状态
|
||||
|
||||
<div align="center"> <img src="../pics//d52270b4-9097-4667-9f18-f405fc661c99.png"/> </div><br>
|
||||
|
||||
### 实现
|
||||
|
||||
```java
|
||||
public interface Flyweight {
|
||||
void doOperation(String extrinsicState);
|
||||
}
|
||||
```
|
||||
|
||||
```java
|
||||
public class ConcreteFlyweight implements Flyweight {
|
||||
|
||||
private String intrinsicState;
|
||||
|
||||
public ConcreteFlyweight(String intrinsicState) {
|
||||
this.intrinsicState = intrinsicState;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doOperation(String extrinsicState) {
|
||||
System.out.println("Object address: " + System.identityHashCode(this));
|
||||
System.out.println("IntrinsicState: " + intrinsicState);
|
||||
System.out.println("ExtrinsicState: " + extrinsicState);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```java
|
||||
import java.util.HashMap;
|
||||
|
||||
public class FlyweightFactory {
|
||||
|
||||
private HashMap<String, Flyweight> flyweights = new HashMap<>();
|
||||
|
||||
Flyweight getFlyweight(String intrinsicState) {
|
||||
if (!flyweights.containsKey(intrinsicState)) {
|
||||
Flyweight flyweight = new ConcreteFlyweight(intrinsicState);
|
||||
flyweights.put(intrinsicState, flyweight);
|
||||
}
|
||||
return flyweights.get(intrinsicState);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```java
|
||||
public class Client {
|
||||
public static void main(String[] args) {
|
||||
FlyweightFactory factory = new FlyweightFactory();
|
||||
Flyweight flyweight1 = factory.getFlyweight("aa");
|
||||
Flyweight flyweight2 = factory.getFlyweight("aa");
|
||||
flyweight1.doOperation("x");
|
||||
flyweight2.doOperation("y");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```html
|
||||
Object address: 1163157884
|
||||
IntrinsicState: aa
|
||||
ExtrinsicState: x
|
||||
Object address: 1163157884
|
||||
IntrinsicState: aa
|
||||
ExtrinsicState: y
|
||||
```
|
||||
|
||||
### JDK
|
||||
|
||||
|
|
BIN
pics/d52270b4-9097-4667-9f18-f405fc661c99.png
Normal file
BIN
pics/d52270b4-9097-4667-9f18-f405fc661c99.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 19 KiB |
Loading…
Reference in New Issue
Block a user