码迷,mamicode.com
首页 > 编程语言 > 详细

[20-05-14][Thinking in Java 15]Java Interfaces 4 - Factories 2

时间:2020-05-15 00:34:12      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:new   ret   str   bool   main   ati   pac   factory   code   

1 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 0
Checkers move 1
Checkers move 2
Chess move 0
Chess move 1
Chess move 2
Chess move 3

[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.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!