Java第十一天
- 接口:在Java中,接口是实现可插入特性的保证。定义接口的关键字是interface,实现接口的关键字是implements,一个类可以实现多个接口,接口之间的继承支持多重继承。
接口和抽象类的异同
- 类/类和类/接口之间的关系
- IS-A关系:继承(Generalize)/实现(Realize)
- HAS-A关系:关联(Associate)/聚合(聚集)(Aggregate)/合成(Compose)
- USE-A关系:依赖(Dependency)
- UML:统一建模语言(标准的图形化符号)
- 类图:描述类以及类和类之间关系的图形符号。
- 用例图:捕获需求。
- 时序图:描述对象交互关系。
- 面向对象的设计原则
- 单一职责原则(SRP):类的设计要做到高内聚,一个类只承担单一的职责(不做不该它做的事情)。
- 开闭原则(OCP):软件系统应该接受扩展(对扩展开放),不接受修改(对修改关闭)。要符合开闭原则:抽象是关键,封装可变性。
- 依赖倒转原则(DIP):面向接口编程。声明变量的引用类型,声明方法的参数类型,声明方法的返回类型时,尽可能使用抽象类型而不是具体类型。
- 里氏替换原则(LSP):用子类型替换父类型没有任何问题,用父类型替换子类型通常都是不行的。
- 接口隔离原则(ISP):接口要小而专,不能大而全。
- 合成聚合复用原则(CARP):优先考虑用强关联关系复用代码,而不是用继承关系复用代码。
- 迪米特法则(LoD):对象之间尽可能少的发生联系。
练习一:
package day0513;
import java.awt.Graphics;
/**
* 能否在窗口上绘图的接口
* @author jackfrued
*
*/
public interface Drawable {
/**
* 绘图
* @param g 画笔对象
*/
public abstract void draw(Graphics g);
}
package day0513;
import java.awt.Color;
/**
* 图形(抽象类)
* @author A
*
*/
public abstract class Shape implements Drawable {
protected int x; // 中心的横坐标
protected int y; // 中心的纵坐标
protected Color color; // 颜色
/**
* 计算面积
* @return 图形的面积
*/
public abstract double area();
/**
* 计算周长
* @return 图形的周长
*/
public abstract double perimeter();
public void setColor(Color color) {
this.color = color;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
package day0513;
import java.awt.Graphics;
/**
* 圆
* @author A
*
*/
public class Circle extends Shape {
private int radius; // 半径
/**
* 构造器
* @param radius 半径
*/
public Circle(int radius) {
this.radius = radius;
}
@Override
public void draw(Graphics g) {
g.setColor(color);
g.drawOval(x - radius, y - radius, 2 * radius, 2 * radius);
}
@Override
public double area() {
return Math.PI * radius * radius;
}
@Override
public double perimeter() {
return 2 * Math.PI * radius;
}
}
package day0513;
import java.awt.Graphics;
/**
* 矩形
* @author A
*
*/
public class Rect extends Shape {
private int width; // 宽
private int height; // 高
/**
* 构造器
* @param width 宽
* @param height 高
*/
public Rect(int width, int height) {
this.width = width;
this.height = height;
}
@Override
public void draw(Graphics g) {
g.setColor(color);
g.drawRect(x - width / 2, y - height / 2, width, height);
}
@Override
public double area() {
return width * height;
}
@Override
public double perimeter() {
return (width + height) << 1;
}
}
package day0513;
import java.awt.Graphics;
/**
* 等边三角形
* @author A
*
*/
public class Triangle extends Shape {
private int edge;
/**
* 构造器
* @param edge 变长
*/
public Triangle(int edge) {
this.edge = edge;
}
@Override
public void draw(Graphics g) {
int ax = x;
int ay = (int) (y - edge * Math.cos(Math.PI / 6)
+ edge / 2 * Math.tan(Math.PI / 6));
int bx = x - edge / 2;
int by = (int) (y + edge / 2 * Math.tan(Math.PI / 6));
int cx = x + edge / 2;
int cy = (int) (y + edge / 2 * Math.tan(Math.PI / 6));
g.setColor(color);
g.drawLine(ax, ay, bx, by);
g.drawLine(bx, by, cx, cy);
g.drawLine(cx, cy, ax, ay);
}
@Override
public double area() {
double s = perimeter() / 2;
return Math.sqrt(s * Math.pow(s - edge, 3));
}
@Override
public double perimeter() {
return 3 * edge;
}
}
package day0513;
import java.awt.Color;
/**
* 自定义工具类
* @author A
*
*/
public final class MyUtil {
private MyUtil() {
}
/**
* 产生指定范围的随机整数
* @param min 最小值(闭区间)
* @param max 最大值(闭区间)
* @return 指定范围的随机整数
*/
public static int random(int min, int max) {
return (int) (Math.random() * (max - min + 1) + min);
}
/**
* 生成随机颜色
* @return Color对象
*/
public static Color randomColor() {
int r = random(0, 255);
int g = random(0, 255);
int b = random(0, 255);
return new Color(r, g, b);
}
}
package day0513;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
@SuppressWarnings("serial")
public class DrawingFrame extends JFrame implements ActionListener {
private List<Shape> shapeList = new ArrayList<Shape>();
private List<Shape> redoList = new ArrayList<Shape>();
private JButton circleButton, rectButton, triButton;
private JButton undoButton, redoButton, clearButton;
private Shape shape = null;
private String shapeType = "Circle";
public DrawingFrame() {
this.setSize(800, 600);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
circleButton = new JButton("Circle");
circleButton.addActionListener(this);
rectButton = new JButton("Rectangle");
rectButton.addActionListener(this);
triButton = new JButton("Triangle");
triButton.addActionListener(this);
undoButton = new JButton("撤销");
undoButton.addActionListener(this);
redoButton = new JButton("恢复");
redoButton.addActionListener(this);
clearButton = new JButton("清空");
clearButton.addActionListener(this);
this.setLayout(new FlowLayout());
this.add(circleButton);
this.add(rectButton);
this.add(triButton);
this.add(undoButton);
this.add(redoButton);
this.add(clearButton);
this.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if(shapeType.equals("Circle")) {
int radius = MyUtil.random(10, 280);
shape = new Circle(radius);
}
else if(shapeType.equals("Rectangle")) {
int width = MyUtil.random(10, 550);
int height = MyUtil.random(10, 550);
shape = new Rect(width, height);
}
else if(shapeType.equals("Triangle")) {
int edge = MyUtil.random(50, 300);
shape = new Triangle(edge);
}
if(shape != null) {
shape.setX(e.getX());
shape.setY(e.getY());
Color color = MyUtil.randomColor();
shape.setColor(color);
shapeList.add(shape);
repaint();
}
}
});
}
@Override
public void paint(Graphics g) {
super.paint(g);
for(Shape tempShape : shapeList) {
tempShape.draw(g);
g.drawString(
String.format("周长: %.2f", tempShape.perimeter()),
tempShape.getX(), tempShape.getY());
g.drawString(
String.format("面积: %.2f", tempShape.area()),
tempShape.getX(), tempShape.getY() + 15);
}
}
public static void main(String[] args) {
new DrawingFrame().setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == circleButton) {
shapeType = "Circle";
}
else if(e.getSource() == rectButton) {
shapeType = "Rectangle";
}
else if(e.getSource() == triButton) {
shapeType = "Triangle";
}
else if(e.getSource() == undoButton) {
if(shapeList.size() > 0) {
Shape temp = shapeList.remove(shapeList.size() - 1);
redoList.add(temp);
repaint();
}
}
else if(e.getSource() == redoButton) {
if(redoList.size() > 0) {
Shape temp = redoList.remove(redoList.size() - 1);
shapeList.add(temp);
repaint();
}
}
else if(e.getSource() == clearButton) {
shapeList.clear();
repaint();
}
}
}
练习二
创建五子棋棋盘:
package day0513;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
/**
* 棋盘
* @author A
*
*/
public class Board {
private static final int CELL_SIZE = 40;
private CellState[][] board = new CellState[15][15];
private int lastRow = -1, lastCol = -1;
public Board() {
reset();
}
/**
* 走棋
* @param row 落子的行
* @param col 落子的列
* @param isBlack 是不是黑棋
* @return 如果落子成功返回true否则返回false
*/
public boolean move(int row, int col, boolean isBlack) {
if(board[row][col] == CellState.Empty) {
board[row][col] = isBlack? CellState.Black : CellState.White;
lastRow = row;
lastCol = col;
return true;
}
return false;
}
/**
* 绘制棋盘和棋子
* @param g 画笔
*/
public void draw(Graphics g) {
// 纵横15条线
for(int i = 0; i < board.length; i++) {
g.drawLine(30, 30 + CELL_SIZE * i, 590, 30 + CELL_SIZE * i);
g.drawLine(30 + CELL_SIZE * i, 30, 30 + CELL_SIZE * i, 590);
}
g.fillOval(305, 305, 10, 10); // 天元
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(3)); // 将画笔变粗
g.drawRect(25, 25, 570, 570); // 外边框
// 对棋盘的行和列进行循环绘制棋子
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[i].length; j++) {
if(board[i][j] != CellState.Empty) { // 不是空白
Color color = board[i][j] == CellState.Black? Color.BLACK : Color.WHITE;
g.setColor(color);
g.fillOval(10 + CELL_SIZE * j, 10 + CELL_SIZE * i,
CELL_SIZE, CELL_SIZE);
}
}
}
if(lastRow != -1 && lastCol != -1) {
g.setColor(Color.RED);
g.drawLine(25 + CELL_SIZE * lastCol, 30 + CELL_SIZE * lastRow,
35 + CELL_SIZE * lastCol, 30 + CELL_SIZE * lastRow);
g.drawLine(30 + CELL_SIZE * lastCol, 25 + CELL_SIZE * lastRow,
30 + CELL_SIZE * lastCol, 35 + CELL_SIZE * lastRow);
}
}
/**
* 重置棋盘
*/
public void reset() {
lastRow = -1;
lastCol = -1;
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[i].length; j++) {
board[i][j] = CellState.Empty;
}
}
}
}
package day0513;
/**
* 枚举法
* @author A
*
*/
public enum CellState {
Empty, Black, White
}
package day0513;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
/**
* 窗口
* @author A
*
*/
@SuppressWarnings("serial")
public class RenjuDialog extends JDialog {
private RenjuPanel panel = new RenjuPanel();
public RenjuDialog() {
this.setTitle("五子棋");
this.setSize(625, 645);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setIconImage(new ImageIcon("renju.png").getImage());
this.add(panel);
this.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_F2) { //使用F2重置游戏
panel.reset();
repaint();
}
}
});
}
public static void main(String[] args) {
new RenjuDialog().setVisible(true);
}
}
package day0513;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
import javax.swing.Timer;
/**
* 五子棋的面板
* @author A
*
*/
@SuppressWarnings("serial")
public class RenjuPanel extends JPanel {
private Timer timer = null;
private Board b = new Board(); // 创建棋盘对象
private boolean isBlack = true; // 是否黑方走棋
private boolean gameBegin = false; // 游戏是否开始
public RenjuPanel() {
this.setSize(620, 620);
this.addMouseListener(new MouseAdapter() { // 添加鼠标事件监听器监听鼠标按下事件
@Override
public void mousePressed(MouseEvent e) {
if(gameBegin) {
int x = e.getX();
int y = e.getY();
if(x >= 20 && x <= 600 && y >= 20 && y <= 600) {
int row = Math.round((y - 30) / 40.0f);
int col = Math.round((x - 30) / 40.0f);
if(b.move(row, col, isBlack)) { // 在鼠标点击位置走棋
isBlack = !isBlack;
repaint();
}
}
}
}
});
timer = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int row = (int) (Math.random() * 15);
int col = (int) (Math.random() * 15);
if(b.move(row, col, isBlack)) {
isBlack = !isBlack;
repaint();
}
}
});
timer.start();
}
@Override
public void paint(Graphics g) {
super.paint(g);
// 绘制背景
g.setColor(Color.ORANGE);
g.fillRect(0, 0, 620, 620);
// 绘制棋盘
g.setColor(Color.BLACK);
b.draw(g);
}
/**
* 重置五子棋面板
*/
public void reset() {
timer.stop();
b.reset();
isBlack = true;
gameBegin = true;
}
}