java设计模式---享元模式

内存属于稀缺资源,不要随便浪费,如果有很多个相同或者相似的对象,我们就可以通过享元模式来节省内存。
享元对象能做到共享的关键是区分了内部状态和外部状态。
内部状态:可以共享,不会随外部状态的改变而改变。
外部状态:不可以共享,会随外部状态的改变而改变。

这里写图片描述

这里写图片描述

以围棋的棋子为例子,其大小形状相同,颜色分为黑白,只有位置信息不同。
看代码:

interface ChessFlyWeight {
    void setColor(String c);

    String getColor();

    void display(Coordinate c);
}

class ConcreteChess implements ChessFlyWeight {
    private String color;

    public ConcreteChess(String color) {
        super();
        this.color = color;
    }

    @Override
    public void setColor(String c) {
        // TODO Auto-generated method stub
        this.color = c;
    }

    @Override
    public String getColor() {
        // TODO Auto-generated method stub
        return this.color;
    }

    @Override
    public void display(Coordinate c) {
        // TODO Auto-generated method stub
        System.out.println("棋子颜色:" + color);
        System.out.println("棋子位置:" + c.getX() + "----" + c.getY());
    }

}
class Coordinate {
    int x, y;

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

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }
}

享元工厂类:

class ChessFlyWeightFactory{
    static Map<String,ChessFlyWeight> map=new HashMap<String, ChessFlyWeight>();

    public static ChessFlyWeight getChess(String c){
        if(map.get(c)!=null){
            return map.get(c);
        }else{
            ChessFlyWeight ct=new ConcreteChess(c);
            map.put(c,ct);
            return ct;
        }
    }
}

最后看测试类

public class TestFlyWeight {

    public static void main(String[] args) {
        ChessFlyWeight c1=ChessFlyWeightFactory.getChess("白色");
        c1.display(new Coordinate(10, 10));
        System.out.println(c1);
        ChessFlyWeight c2=ChessFlyWeightFactory.getChess("白色");
        c2.display(new Coordinate(20, 20));
        System.out.println(c2);
    }
}

测试结果:
这里写图片描述

但是,享元模式为了节省内存,共享了内部状态,分离了外部状态,而读取外部状态增加了运行时间,即用时间换取了空间。

应用场景:
1:享元模式由于其共享的特性,可以在任何“池”中操作,比如线程池,数据库连接池。
2:String类的设计也是运用了享元模式。

发布了21 篇原创文章 · 获赞 9 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/coding_man_xie/article/details/49562159