[20-05-14][Thinking in Java 15]Java Interfaces 4 - Factories 2
2021-01-22 03:13
标签:new ret str bool main ati pac factory code 结果如下: Checkers move 0 [20-05-14][Thinking in Java 15]Java Interfaces 4 - Factories 2 标签:new ret str bool main ati pac factory code 原文地址:https://www.cnblogs.com/mirai3usi9/p/12892135.html1 package test_12_2;
2
3 public interface Game {
4
5 boolean move();
6 }
1 package test_12_2;
2
3 public interface GameFactory {
4
5 Game getGame();
6 }
1 package test_12_2;
2
3 public class Checkers implements Game {
4
5 private int moves = 0;
6 private static final int MOVES = 3;
7
8 public boolean move() {
9
10 System.out.println("Checkers move " + moves);
11 return ++moves != MOVES;
12 }
13 }
1 package test_12_2;
2
3 public class CheckersFactory implements GameFactory {
4
5 public Game getGame() {
6
7 return new Checkers();
8 }
9 }
1 package test_12_2;
2
3 public class Chess implements Game {
4
5 private int moves = 0;
6 private static final int MOVES = 4;
7
8 public boolean move() {
9
10 System.out.println("Chess move " + moves);
11 return ++moves != MOVES;
12 }
13 }
1 package test_12_2;
2
3 public class ChessFactory implements GameFactory {
4
5 public Game getGame() {
6
7 return new Chess();
8 }
9 }
1 package test_12_2;
2
3 public class Games {
4
5 public static void playGame(GameFactory factory) {
6
7 Game s = factory.getGame();
8 while (s.move()) {
9 ;
10 }
11 }
12
13 public static void main(String[] args) {
14
15 playGame(new CheckersFactory());
16 playGame(new ChessFactory());
17 }
18 }
Checkers move 1
Checkers move 2
Chess move 0
Chess move 1
Chess move 2
Chess move 3
上一篇:五种线程池的分类和作用
下一篇:SpringCloud 使用
文章标题:[20-05-14][Thinking in Java 15]Java Interfaces 4 - Factories 2
文章链接:http://soscw.com/index.php/essay/45259.html