设计模式之蝇量模式

来源:互联网 发布:安东尼戴维斯 数据 编辑:程序博客网 时间:2024/04/30 14:59
模式定义:
        该模式以共享的方式高效地支持大量的细粒度对象。通过复用内存中已经存在的对象,
        降低系统创建对象的性能消耗。
遵循原则:
        共享细粒度对象,降低内存消耗;
        分开变化和不变部分。
适用场合:
        (1)当系统中某对象类型的实例比较多的时候;
        (2)在系统设计时,对象实例进行分类后,发现真正有区别的分类很少的时候。
知识扩展:
        JDK中的String、Integer就是典型的实践者,拼音输入法。享元模式中的对象分为
        内蕴状态【黑还是白】和外蕴状态【位置】。内蕴状态是不会变化的部分,而外蕴状态

        是随外部环境随时会变化的部分,由客户端通过参数的形式传入。

public abstract class AbstractChess {
    
    //棋子位置,外蕴状态,不可以共享
    protected int x;
    protected int y;
    
    
    //棋子类别,内蕴状态,可以共享
    protected String chess;

    public AbstractChess(String chess) {
        this.chess = chess;
    }
    
    public void point(int x,int y){
        this.x = x;
        this.y = y;
        this.show();
    }
    public void show(){
        System.out.println(this.chess+"("+this.x+","+this.y+")");
    }
}

public class BlackChess extends AbstractChess {

    public BlackChess() {
        super("●");
        System.out.println("BlackChess Constructor Used!!");
    }

}

public class WhiteChess extends AbstractChess {

    public WhiteChess() {
        super("○");
        System.out.println("WhiteChess Constructor Used!!");
    }

}

获取棋子的工厂

public class ChessFactory {

    private static ChessFactory chessFactory = new ChessFactory();
    private ChessFactory() {
    }
    public static ChessFactory getFactoryInstance(){
        return chessFactory;
    }
    
    
    private final Hashtable<Character, AbstractChess> chache = new Hashtable<Character, AbstractChess>();
    
    /**
     * 缓存中有则直接拿出,没有则先新建,放入,返回,返回后的棋子可以改变其外蕴状态
     */
    public AbstractChess getChessObject(Character c){
        AbstractChess abChess = chache.get(c);
        if(abChess == null){
            switch (c) {
            case 'B':
                abChess = new BlackChess();
                break;
            case 'W':
                abChess = new WhiteChess();
                break;

            default:
                break;
            }
            
            if(abChess != null){
                chache.put(c, abChess);
            }
        }
        return abChess;
    }
}

测试

public class Client {
    public static void main(String[] args) {
        ChessFactory cFactory = ChessFactory.getFactoryInstance();
        AbstractChess abstractChess = null;
        Random random = new Random();
        int radom = 0;
        
        for (int i = 0; i < 10; i++) {
            radom = random.nextInt(2);
            switch (radom) {
            case 0:
                abstractChess = cFactory.getChessObject('B');
                break;
            case 1:
                abstractChess = cFactory.getChessObject('W');
                break;

            default:
                break;
            }
            if(abstractChess != null){
                abstractChess.point(i, random.nextInt(15));
//                abstractChess.show();
            }
        }
    }

}

0 0