java 接口与工厂

接口时实现多重继承的途径,而生产遵循某个接口的对象的典型方式就是工厂方法设计模式,这与直接调用构造器不同,我们在工厂对象上调用的是某种方法,而该工厂对象将生成接口的某个实现的对象,理论上通过这种方式,我们的代码将完全与接口的实现分离,这就使得我们可以透明地将某个实现替换为另一个实现

//如果不适应工厂模式,你的代码就必须在某处指定将要创建的service的确切类型,以便调用合适的构造器
//
: interfaces/Factories.java package object; import static net.mindview.util.Print.*; interface Service { void method1(); void method2(); } interface ServiceFactory { Service getService(); } class Implementation1 implements Service { Implementation1() {} // Package access public void method1() {print("Implementation1 method1");} public void method2() {print("Implementation1 method2");} } class Implementation1Factory implements ServiceFactory { public Service getService() { return new Implementation1(); } } class Implementation2 implements Service { Implementation2() {} // Package access public void method1() {print("Implementation2 method1");} public void method2() {print("Implementation2 method2");} } class Implementation2Factory implements 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(new Implementation1Factory()); // Implementations are completely interchangeable: serviceConsumer(new Implementation2Factory()); } } /* Output: Implementation1 method1 Implementation1 method2 Implementation2 method1 Implementation2 method2 *///:~

使用工厂模式一个常见的原因是想要创建框架,假设正在创建一个对弈游戏系统,例如在棋盘上下国际象棋和西洋象棋

//如果Games 是一段复杂的代码,那么这种方式就允许你在不同类型的游戏中复用这段代码
//
: interfaces/Games.java // A Game framework using Factory Methods. package object; import static net.mindview.util.Print.*; interface Game { boolean move(); } interface GameFactory { Game getGame(); } class Checkers implements Game { private int moves = 0; private static final int MOVES = 3; public boolean move() { print("Checkers move " + moves); return ++moves != MOVES; } } class CheckersFactory implements GameFactory { public Game getGame() { return new Checkers(); } } class Chess implements Game { private int moves = 0; private static final int MOVES = 4; public boolean move() { print("Chess move " + moves); return ++moves != MOVES; } } class ChessFactory implements 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(new CheckersFactory()); playGame(new ChessFactory()); } } /* Output: Checkers move 0 Checkers move 1 Checkers move 2 Chess move 0 Chess move 1 Chess move 2 Chess move 3 *///:~

 

posted @ 2019-01-03 15:08  江期玉  阅读(707)  评论(0编辑  收藏  举报