享元设计模式(卡牌示例)
0. UML结构图
![享元模式UML结构图](https://i-blog.csdnimg.cn/blog_migrate/e0e87bb44969b919caeb84c814f813c2.png)
1. 卡牌享元示例Code
1.1 卡牌接口
public interface FlyWeight {
void setShape(String shape);
String getShape();
void show(View view);
}
1.2 卡牌实现类 - 内部状态
public class Card implements FlyWeight {
private String shape;
public Card(String shape) {
this.shape = shape;
}
@Override
public void setShape(String shape) {
this.shape = shape;
}
@Override
public String getShape() {
return shape;
}
@Override
public void show(View view) {
System.out.println("shape = " + shape);
System.out.println("view = " + view);
}
}
1.3 卡牌画面 - 外部状态
public class View {
private String letter;
public View(String letter) {
this.letter = letter;
}
public String getLetter() {
return letter;
}
public void setLetter(String letter) {
this.letter = letter;
}
@Override
public String toString() {
return "View{" +
"letter='" + letter + '\'' +
'}';
}
}
1.4 卡牌工厂 - 享元工厂
public class CardFactory {
private static Map<String, Card> map = new HashMap<>();
public static Card getCard(String shape) {
return map.computeIfAbsent(shape, Card::new);
}
}
2. 卡牌享元示例Test
public class FlyWeightTest {
public static void main(String[] args) {
Card card1 = CardFactory.getCard("rectangle");
Card card2 = CardFactory.getCard("rectangle");
System.out.println(card1 == card2);
card1.show(new View("A"));
card2.show(new View("B"));
}
}