diff --git a/notes/设计模式.md b/notes/设计模式.md index dc075cf7..6c5e2769 100644 --- a/notes/设计模式.md +++ b/notes/设计模式.md @@ -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:外部状态 + +

+ +### 实现 + +```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 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 diff --git a/pics/d52270b4-9097-4667-9f18-f405fc661c99.png b/pics/d52270b4-9097-4667-9f18-f405fc661c99.png new file mode 100644 index 00000000..347fe316 Binary files /dev/null and b/pics/d52270b4-9097-4667-9f18-f405fc661c99.png differ