ErBing

往事已经定格,未来还要继续。

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

来源:http://www.bjsxt.com/ 
一、【GOF23设计模式】_享元模式、享元池、内部状态、外部状态、线程池、连接池

场景

围棋软件设计

享元模式实现

 1 package com.test.flyweight;
 2 /**
 3  * FlyWeight抽象享元类
 4  */
 5 public interface ChessFlyWeight {
 6     void setColor(String c);
 7     String getColor();
 8     void display(Coordinate c);
 9 }
10 
11 /**
12  * ConcreteFlyWeight具体享元类
13  */
14 class ConcreteChess implements ChessFlyWeight {
15     private String color;
16 
17     public ConcreteChess(String color) {
18         super();
19         this.color = color;
20     }
21 
22     @Override
23     public void setColor(String c) {
24         this.color = c;
25     }
26 
27     @Override
28     public String getColor() {
29         return color;
30     }
31 
32     @Override
33     public void display(Coordinate c) {
34         System.out.println("棋子颜色:"+color);
35         System.out.println("棋子位置:"+c.getX()+"------"+c.getY());
36     }
37 }
 1 package com.test.flyweight;
 2 /**
 3  * 外部状态UnSharedConcreteFlyWeight非共享享元类
 4  */
 5 public class Coordinate {
 6     private int x,y;
 7 
 8     public Coordinate(int x, int y) {
 9         super();
10         this.x = x;
11         this.y = y;
12     }
13 
14     public int getX() {
15         return x;
16     }
17 
18     public void setX(int x) {
19         this.x = x;
20     }
21 
22     public int getY() {
23         return y;
24     }
25 
26     public void setY(int y) {
27         this.y = y;
28     }
29 }
package com.test.flyweight;

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;
        }
    }
}
 1 package com.test.flyweight;
 2 
 3 public class Client {
 4     public static void main(String[] args) {
 5         ChessFlyWeight chess1 = ChessFlyWeightFactory.getChess("黑色");
 6         ChessFlyWeight chess2 = ChessFlyWeightFactory.getChess("黑色");
 7         System.out.println(chess1);
 8         System.out.println(chess2);
 9 
10         System.out.println("增加外部状态的处理============");
11         chess1.display(new Coordinate(10,10));
12         chess2.display(new Coordinate(20,20));  
13     }
14 }
控制台输出:
com.test.flyweight.ConcreteChess@1db9742
com.test.flyweight.ConcreteChess@1db9742
增加外部状态的处理============
棋子颜色:黑色
棋子位置:10------10
棋子颜色:黑色
棋子位置:20------20

享元模式实现的UML图

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

优点

posted on 2016-08-24 13:36  ErBing  阅读(203)  评论(0编辑  收藏  举报