1. 程式人生 > >java 內部類 工廠方法

java 內部類 工廠方法

用內部類實現工廠模式 :優先使用類而不是介面,如果你的設計中需要某個介面,你必須瞭解它,否則不到迫不得已,不要將其放到你的類中

//: innerclasses/Factories.java
import static net.mindview.util.Print.*;

interface Service {
  void method1();
  void method2();
}

interface ServiceFactory {
  Service getService();
}    

class Implementation1 implements Service {
  
private Implementation1() {} //構造器可以是private public void method1() {print("Implementation1 method1");} public void method2() {print("Implementation1 method2");} public static ServiceFactory factory = //經常只需要單一的工廠物件,因此用了static域,這樣產生的語法也更有實際意義 new ServiceFactory() { public Service getService() {
return new Implementation1(); } }; } class Implementation2 implements Service { private Implementation2() {} public void method1() {print("Implementation2 method1");} public void method2() {print("Implementation2 method2");} public static ServiceFactory factory = new ServiceFactory() {
public Service getService() { return new Implementation2(); } }; } public class Factories { public static void serviceConsumer(ServiceFactory fact) { Service s = fact.getService(); s.method1(); s.method2(); } public static void main(String[] args) { serviceConsumer(Implementation1.factory); // Implementations are completely interchangeable: serviceConsumer(Implementation2.factory); } } /* Output: Implementation1 method1 Implementation1 method2 Implementation2 method1 Implementation2 method2 *///:~
//: innerclasses/Games.java
// Using anonymous inner classes with the Game framework.
package object;
import static net.mindview.util.Print.*;

interface Game { boolean move(); }
interface GameFactory { Game getGame(); }

class Checkers implements Game {
  private Checkers() {}
  private int moves = 0;
  private static final int MOVES = 3;
  public boolean move() {
    print("Checkers move " + moves);
    return ++moves != MOVES;
  }
  public static GameFactory factory = new GameFactory() {
    public Game getGame() { return new Checkers(); }
  };
}    

class Chess implements Game {
  private Chess() {}
  private int moves = 0;
  private static final int MOVES = 4;
  public boolean move() {
    print("Chess move " + moves);
    return ++moves != MOVES;
  }
  public static GameFactory factory = new GameFactory() {
    public Game getGame() { return new Chess(); }
  };
}    

public class Games {
  public static void playGame(GameFactory factory) {
    Game s = factory.getGame();
    while(s.move())
      ;
  }
  public static void main(String[] args) {
    playGame(Checkers.factory);
    playGame(Chess.factory);
  }
} /* Output:
Checkers move 0
Checkers move 1
Checkers move 2
Chess move 0
Chess move 1
Chess move 2
Chess move 3
*///:~