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 *///:~