11、设计模式(结构型)之享元模式

作用

  • 运用共享技术有效地支持大量细粒度的对象。

何时使用

  1. 系统中有大量对象。
  2. 这些对象消耗大量内存。
  3. 这些对象的状态大部分可以外部化。
  4. 这些对象可以按照内蕴状态分为很多组,当把外蕴对象从对象中剔除出来时,每一组对象都可以用一个对象来代替。
  5. 系统不依赖于这些对象身份,这些对象是不可分辨的。

优点

  • 大大减少对象的创建,降低系统的内存,使效率提高。

实例

/**
 * @Author: create_By: chenxin
 * @Data:Created in 2018/9/3 14:08
 * @Version:
 * @Acton: 外部状态
 */
public class Coordinate {

    private int x;
    private int y;

    public Coordinate(int x, int y) {
        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;
    }
}
/**
 * @Author: create_By: chenxin
 * @Data:Created in 2018/9/3 14:05
 * @Version:
 * @Acton:  享元类
 */
public interface ChessFlyweight {

    void serColor(String color);
    String getColor();
    void display(Coordinate coordinate);
}
class ConcreateChess implements ChessFlyweight {

    private String color;

    public ConcreateChess(String color) {
        this.color = color;
    }

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

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

    @Override
    public void display(Coordinate coordinate) {
        System.out.println("棋子的颜色:" + color);
        System.out.println("棋子的位置:" + coordinate.getX()+ "__" + coordinate.getY());
    }
}
/**
 * @Author: create_By: chenxin
 * @Data:Created in 2018/9/3 14:31
 * @Version:
 * @Acton:  享元工厂类
 */
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 cf = new ConcreateChess(color);
            map.put(color,cf);
            return cf;
        }
    }


}

 

/**
 * @Author: create_By: chenxin
 * @Data:Created in 2018/9/3 11:38
 * @Version:
 * @Acton:  测试享元模式
 */
public class TestFlyWeightDemo {
    
    public static void main(String[] args){
        test1();
    }

    private static void test1() {
        ChessFlyweight chess1 = ChessFlyweightFactory.getChess("黑色");
        ChessFlyweight chess2 = ChessFlyweightFactory.getChess("黑色");
        System.out.println(chess1);
        System.out.println(chess2);

        System.out.println("#====================增加外部状态的处理====================");
        chess1.display(new Coordinate(10,10 ));
        chess1.display(new Coordinate(20,20 ));
    }
}

 

关系图

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值