Thinking in Java 4th chap9笔记-接口(五)

2014-11-24 11:10:32 · 作者: · 浏览: 7
();
void method2();
}
//接口服务工厂
interface ServiceFactory
{
//获取服务
Service getService();
}
//服务实现1
class Implementation1 implements Service
{
@Override
public void method1()
{
System.out.println("Implementation1 method1");
}
@Override
public void method2()
{
System.out.println("Implementation1 method2");
}
}
//服务实现1工厂
class Implementation1Factory implements ServiceFactory
{
@Override
public Service getService()
{
return new Implementation1();
}
}
//服务实现2
class Implementation2 implements Service
{
@Override
public void method1()
{
System.out.println("Implementation2 method1");
}
@Override
public void method2()
{
System.out.println("Implementation2 method2");
}
}
//服务实现2工厂
class Implementation2Factory implements ServiceFactory
{
@Override
public Service getService()
{
return new Implementation2();
}
}
package com.book.chap9.Interface;
/**
*
*如果不是用工厂方法,你的代码就必须在某处指定将要创建的Service确切类型,以便调用合适的构造器。
*为什么我们想要添加这种额外级别的间接性呢?一个常见的原因是想要创建框架:假设你正在创建一个对弈游戏系统,
*例如,在相同的棋盘上下国际象棋和西洋跳棋,如果Games类,处理逻辑,表示一段复杂的代码,那么这种方式允许你在不同类型的游戏中复用这段代码{@link Games}
*
*@author landon
*@since JDK1.6
*@version 1.0 2012-5-15
*
*/
public class Games
{
//玩游戏
public static void playGame(GameFactory factory)
{
Game game = factory.getGame();
while(game.move())
{
//.做其他操作
}
}
//运行游戏,游戏的双方各自操作
public static void main(Stringargs)
{
playGame(new CheckersFactory());
playGame(new ChessFactory());
}
}
interface Game
{
boolean move();
}
interface GameFactory
{
Game getGame();
}
//国际象棋的一方
class Checkers implements Game
{
private int moves = 0;
private static final int MOVES = 3;
@Override
public boolean move()
{
System.out.println("Checkers move: " + moves);
return ++moves != MOVES;
}
}
//CheckersFactory
class CheckersFactory implements GameFactory
{
@Override
public Game getGame()
{
return new Checkers();
}
}
//国际象棋的另一方
class Chess implements Game
{
private int moves = 0;
private static final int MOVES = 4;
@Override
public boolean move()
{
System.out.println("Chess move: " + moves);
return ++moves != MOVES;
}
}
//ChessFactory
class ChessFactory implements GameFactory
{
@Override
public Game getGame()
{
return new Chess();
}
}
package com.book.chap9.Interface;
/**
*
*通过继承来扩展接口
*
*Vampire用到的语法仅适用于接口继承,一般情况下,只可将extends用于单一类,但是可以
*引用多个基类接口
*
*@author landon
*@since JDK1.6
*@version 1.0 2012-5-7
*
*/
public class HorrorShow
{
static void u(Monster m)
{
m.menace();
}
static void v(DangerousMonster m)
{
m.menace();
m.destroy();
}
static void w(Lethal l)
{