享元模式的理解

享元模式的出发点在于减少创建对象的数量,以减少内存占用和提高性能。防止存在大量对象从而导致内存溢出。

享元模式重视重用现有的同类对象,如果未找到匹配的对象,则创建新对象。如果找到匹配的对象,就直接返回对象。

依据上面所说,那么肯定要用到key-value的存储机制 因此使用hashmap进行存储。
应用的场景:在String中我们会发现如下判断是相等的

String str1 = "ABC";
String str2 = "ABC";
System.out.println(str1==str2);

第二个字符串创建时发现存在相同的字符串常量 就直接返回前一个创建的地址。所以他们的地址是相同的。
实例代码
代码介绍,使用两个对象表示棋盘上的棋子。

//享元类  棋的元素
public interface Chess {
    void setColor(String color);
    void display(Coordinate coordinate);
}

class ChessDisplay implements Chess{
    private String color;
    @Override
    public void setColor(String color) {
        this.color = color;
    }

    @Override
    public void display(Coordinate coordinate) {
        System.out.println(color+"棋子的位置是"+coordinate.x+":"+coordinate.y);
    }
}

因为位置是不一样的,所以抽离出来

public class Coordinate {
    public int x;
    public int y;

    public Coordinate(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

享元工厂类

public class FlyWeightFactory {
    private static HashMap<String,Chess> map = new HashMap<>();
    public Chess getChess(String color){
        Chess chess = map.get(color);
        if(chess==null){
            chess = new ChessDisplay();
            chess.setColor(color);
            map.put(color,chess);
        }
        return chess;
    }
}

测试类

public class Client {
    public static void main(String[] args) {
        FlyWeightFactory flyWeightFactory = new FlyWeightFactory();
        Chess black = flyWeightFactory.getChess("black");
        Chess black1 = flyWeightFactory.getChess("black");
        Chess white = flyWeightFactory.getChess("white");
        Chess white1 = flyWeightFactory.getChess("white");

        System.out.println(black.toString());
        System.out.println(black1.toString());
        System.out.println(white.toString());
        System.out.println(white1.toString());


        black.display(new Coordinate(2,4));
        black1.display(new Coordinate(6,8));
        white.display(new Coordinate(9,8));
        white1.display(new Coordinate(9,10));

    }
}

我们发现两颗黑棋的位置是一样的,两颗白棋的位置是一样的。
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值