设计模式——享元模式(FlyWeight)

代码:GitHub

享元设计模式(卡牌示例)

0. UML结构图

享元模式UML结构图

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<>();

    /**
     * 根据key去map取value,如果不存在,就new一个
     * @param shape 卡牌形状
     * @return 卡牌
     */
    public static Card getCard(String shape) {
        // 和下面注释掉的部分等价
        return map.computeIfAbsent(shape, Card::new);
    }

    /*public static Card getCard(String shape) {
        Card card = map.get(shape);
        if (card == null) {
            card = new Card(shape);
            map.put(shape, card);
        }
        return card;
    }*/

}

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"));
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值