标签搜索

目 录CONTENT

文章目录

元胞自动机之策略模式

陈铭
2021-04-24 / 0 评论 / 0 点赞 / 153 阅读 / 366 字 / 正在检测是否收录...

什么是策略模式

主要角色

如图所示,context依赖策略对象接口,该模式下context会调用接口方法;Strategy是策略接口,它定义了策略对象应该必备的功能(API);ConcreteStrategy是接口的实现类,它详细定义了该对象应该对应的api及其业务逻辑。
image

元胞自动机内的体现

体现

由于涉及到课题,论文也未发表,就节选一点儿代码。主要是关于cell如何展示画面,也就是swing包有关的代码。

public interface Cell {
    public void draw(Graphics g);

    int getY();

    int getX();
}


public class Soot implements Cell{
    private int x;
    private int y;
    private int distinction=0;
    private static int velocity= SootVariable.sootVelocity;

    public Soot(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public int getX() {
        return x;
    }

    @Override
    public int getY() {
        return y;
    }

    public int getDistinction() {
        return distinction;
    }

    public static int getVelocity() {
        return velocity;
    }

    @Override
    public void draw(Graphics g) {
        g.setColor(Color.black);
        g.fillRect(x * cellWidth, y * cellWidth, cellWidth, cellWidth);
    }
}


//repaint执行
    @Override
    protected void paintComponent(Graphics g) {
        for (int i = 0; i < xx.length; i++) {
            for (int j = 0; j < xx[0].length; j++) {
                xx[i][j].draw(g);
            }
        }
        for (int i = 0; i < xx.length; i++) {
            for (int j = 0; j < xx[0].length; j++) {
                if (xx[i][j]!=null) {
                    Human human = (Human) xx[i][j];
                    xx[i][j].draw(g);
                }
            }
        }
    }

因此,每次repaint时候,都不用if-else判断是什么元胞,去执行绘图的逻辑。抽象为接口,接口的实现是什么api逻辑,就执行什么逻辑。

0

评论区