享元模式

2017-08-12  本文已影响0人  会思考的鸭子

场景

如果有很多个完全相同或相似的对象,我们可以通过享元模式,节省内存。

核心

围棋举例

享元模式实现

UML

image.png

代码实现

package com.amberweather.flyweight;
/**
 * 享元类
 * @author HT
 *
 */
public interface ChessFlyweight {
    void setColor(String c);
    String getColor();
    void dispaly(Coordinate c);
}
class ConcreateChess implements ChessFlyweight{
    private String color;
    
    
    public ConcreateChess(String color) {
        super();
        this.color = color;
    }

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

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

    @Override
    public void dispaly(Coordinate c) {
        System.out.println("棋子颜色"+color);
        System.out.println("棋子位置:"+c.getX()+","+c.getY());
    }
    
}
package com.amberweather.flyweight;
/**
 * 
 * 外部状态 UnsharedConcreateFlyWeight
 * @author Administrator
 *
 */
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 com.amberweather.flyweight;

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

/**
 * 享元工厂
 * @author HT
 *
 */
public class ChessFlyWeightFactory {
    private static Map<String,ChessFlyweight> map = new HashMap<>();
    public static ChessFlyweight getChess(String color){
        if (map.get(color) != null){
            return map.get(color);
        }else{
            ChessFlyweight cfw = new ConcreateChess(color);
            map.put(color, cfw);
            return cfw;
        }
    }
}
package com.amberweather.flyweight;

public class Client {

    public static void main(String[] args) {
        ChessFlyweight chess1  =ChessFlyWeightFactory.getChess("黑色");
        ChessFlyweight chess2  =ChessFlyWeightFactory.getChess("黑色");
        System.out.println(chess1);
        System.out.println(chess1);
        
        System.out.println("增加外部状态的处理==========");
        System.out.println("chess1----" );
        chess1.dispaly(new Coordinate(20,20));
        
        System.out.println("chess2----" );
        chess2.dispaly(new Coordinate(30,20));
    }

}

应用场景

上一篇 下一篇

猜你喜欢

热点阅读