设计模式--享元模式(Flyweight)

一、享元模式

这里写图片描述


1.2 UML

这里写图片描述


1.3 享元模式开发中的应用场景

  • 享元模式由于其共享的特性,可以在任何中操作,比如:线程池、数据库连接池

  • String类的设计也是享元模式。

1.4 优劣

  • 极大减少内存中对象的数量
  • 相同或相似对象内存中只存一份,极大的节约资源,提供系统性能
  • 外部状态相对独立,不影响内部状态

  • 模式较复杂,使程序逻辑复杂化
  • 为了节省内存,共享了内部状态,分离出外部状态,而读取外部状态使运行时间变长。用时间换取空间。

1.5 应用场景

这里写图片描述


这里写图片描述


1.5.1 代码

/**
 * 享元类
 */
public 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 display(Coordinate c) {
        System.out.println("棋子颜色:"+color);
        System.out.println("棋子位置:"+c.getX()+"----"+c.getY());
    }

    @Override
    public String getColor() {
        return color;
    }

    @Override
    public void setColor(String c) {
        this.color = c;
    }

}



/**
 * 外部状态UnSharedConcreteFlyWeight
 *
 */
public class Coordinate {
    private 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;
    }

}


import java.util.HashMap;
import java.util.Map;

/**
 * 享元工厂类
 *
 */
public class ChessFlyWeightFactory {
    //享元池
    private static Map<String,ChessFlyWeight> map = new HashMap<String, ChessFlyWeight>();

    public static ChessFlyWeight  getChess(String color){

        if(map.get(color)!=null){
            return map.get(color);
        }else{
            ChessFlyWeight cfw = new ConcreteChess(color);
            map.put(color, cfw);
            return cfw;
        }

    }


}


package flyWeight;

public class Client {

    /**
     * @param args
     */
    public static void main(String[] args) {


        ChessFlyWeight chess1 =  ChessFlyWeightFactory.getChess("白色棋子");
        ChessFlyWeight chess2 =  ChessFlyWeightFactory.getChess("白色棋子");

        System.out.println(chess1);
        System.out.println(chess2);

        System.out.println("增加外部特性");

        chess1.disPlay(new Coordinate(20,10));
        chess1.disPlay(new Coordinate(0,0));
    }


}

工厂模式,在这个地方有关键的作用,到达了共享特性(两个棋子是同一个对象)

flyWeight.ConcreteChessFlyWeight@525483cd
flyWeight.ConcreteChessFlyWeight@525483cd
增加外部特性
棋子颜色:白色棋子
棋子位置:20-------10
棋子颜色:白色棋子
棋子位置:0-------0

参考

高淇三百集之设计模式

猜你喜欢

转载自blog.csdn.net/qq_31156277/article/details/80761661