标签: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