享元模式

2019-05-07  本文已影响0人  Davisxy

场景

核心

享元模式实现

小栗子

package flyweight;

/**
 * 享元类
 * 
 * @author xy
 *
 */
public interface ChessFlyWeight {

    String getColor();

    void setColor(String c);

    void display(Coordinate c);
}

class ConcreteChess implements ChessFlyWeight {
    private String color;

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

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

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

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

}
package flyweight;

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;
    }
    
}
package flyweight;

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

/**
 * 享元工厂
 * 
 * @author xy
 *
 */
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 {
    
    public static void main(String[] args) {
        ChessFlyWeight chessFlyWeight1=ChessFlyWeightFactory.getChess("黑色");
        ChessFlyWeight chessFlyWeight2=ChessFlyWeightFactory.getChess("黑色");
        System.out.println(chessFlyWeight1);
        System.out.println(chessFlyWeight2);
        
        System.out.println("增加外部状态的处理=============");
        chessFlyWeight1.display(new Coordinate(10, 10));
        chessFlyWeight2.display(new Coordinate(20, 20));
    }

}
运行结果:
flyweight.ConcreteChess@15db9742
flyweight.ConcreteChess@15db9742
增加外部状态的处理=============
棋子颜色黑色
旗子位置:10----------10
棋子颜色黑色
旗子位置:20----------20
享元模式.png

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

优点

缺点

上一篇 下一篇

猜你喜欢

热点阅读